var ignore_form_errors = false; // variable for testing to submit forms even when an error is detected

// I don't believe that this is in use as of May 08 - PF
// document.getElementsByAttribute = function(attribute, parentElement) {
//   var children = ($(parentElement) || document.body).getElementsByTagName('*');
//   return $A(children).inject([], function(elements, child) {
//     if (child.getAttribute(attribute))
//       elements.push(Element.extend(child));
//     return elements;
//   });
// }

function validateReferCondition() {
	if($('refer_friend_condition_required') && !$('refer_friend_condition').checked) {
		$('refer_error').innerHTML = $('refer_friend_condition_error').value
		return false;	
	}	else {
		return true;
	}
}

function sendEmailTemplateTest() {
	$('test_result').hide();
	$('email_test_spinner').show();
	var email_template_id = $('email_template_id').value;
	var params = Form.serialize($('email_template_test_form'));
  new Ajax.Request('/email_templates/send_test/' + email_template_id, {
		method: 'post',
		parameters: params,
    onSuccess: function(transport) {
			$('email_test_spinner').hide();
			$('test_result').innerHTML = "Email sent";
			$('test_result').show();			
    },
 		onFailure: function(transport) {
			$('test_result').innerHTML = "Failed to send email";
			$('test_result').show();
			$('email_test_spinner').hide();
		}
  });	
}

function getWindowMetrics(){
  if (self.innerWidth) {
		frameWidth = self	.innerWidth;
		frameHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientWidth) {
    frameWidth = document.documentElement.clientWidth;
    frameHeight = document.documentElement.clientHeight; 
  } else if (document.body) {
    frameWidth = document.body.clientWidth;
    frameHeight = document.body.clientHeight;
  }
  return {height: parseInt(frameHeight), width: parseInt(frameWidth)};
}

function getScrollHeight(){
  var y;
  // all except Explorer
  if (self.pageYOffset) {
      y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
      y = document.documentElement.scrollTop;
  } else if (document.body)	{
      y = document.body.scrollTop;
  }
  return parseInt(y) + getWindowMetrics().height;
}

function target(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

function prepParams(text) {
  return text.replace(/\$/g, "%24").replace(/\&/g, "%26").replace(/\+/g, "%2B").replace(/\,/g, "%2C").replace(/\//g, "%2F").replace(/\:/g, "%3A").replace(/\;/g, "%3B").replace(/\=/g, "%3D").replace(/\?/g, "%3F").replace(/\@/g, "%40");
}

function toggleVisor() {
  if ($('swn_topmenu').visible()) {
   new Effect.BlindUp('swn_topmenu', {duration: 0.2});
  } else {
   new Effect.BlindDown('swn_topmenu', {duration: 0.2});
   new Ajax.Updater('swn_topmenu', '/visor', {method: 'get'});
  }
  $("swn_expand_active").toggleClassName("swn_expand_active");
}


function ackNotifications() {
  new Ajax.Request('/users/ack_notifications', {
    onSuccess: function(transport) {
      $('notification_message').innerHTML = '';
      $('notification_read_link').innerHTML = '';
    }
  });  
}

function approvalAction(id, action) {
  var social_networks = $("social_networks_" + id).checked ? "1" : "0";
  var badge_name = $("badge_name_" + id).innerHTML;
  new Ajax.Request("/users/approval_action/" + id, {
    parameters: "activity=" + action + "&social_networks=" + social_networks,
    onSuccess: function(transport) {
      if (action == "approve") {
        if ($("show_on_network").value == "1") {
          message = "<p><strong>The #{badge} has been approved and posted on your Social Tools.</strong></p>".interpolate({badge: badge_name});
        } else {
          message = "<p><strong>The #{badge} has been approved.</strong><br/><br/>".interpolate({badge: badge_name});
          message += "In order to show these badges on your social networks please add the badge trays to your desired social networks on the right hand side.</p>";
        }
      } else {
        message = "<p><strong>You have rejected the #{badge}.</strong></p>".interpolate({badge: badge_name});
      }
      $("badge_info_" + id).update(message);
      $("approvalItem_" + id).removeClassName("incomplete").addClassName("complete");
      if ($("show_on_network").value == "0") {
        $("no_badges").hide();
        $("approved_badges").show();
        $("show_on_network").value = "1";
        $("add_button").shake();
      }
      list = $$(".incomplete");
      if (list.length > 0) {
        location.hash = list[0].id;
      } else {
        $("no_more_badges").show();
        location.hash = "no_more_badges";
      }
    }
  });
}

function approve_badges_fb_approve(id) {
  new Ajax.Request("/users/approval_action/" + id, {
    parameters: "activity=approve",
    onSuccess: function(transport) {
			Element.replace('approve_badges_fb_reward_link_' + id, 'Badge sent to your FB account');
    }
  });
}

function videoLookup() {
  if ($("video_youtube_code").value) {
    var code = $("video_youtube_code").value;
    if (code.length > 11) {
      $("video_youtube_code").value = /[A-Za-z\d_-]{11}/.exec(code)[0];
      code = $("video_youtube_code").value;
    }
  } else {
    var code = $("video_youtube_code").innerHTML;
  }
  if (code.length == 11) {
    $("video_youtube_code").removeClassName("bad_youtube");
    new Ajax.Request("/videos/youtube_info/" + code, {
      onSuccess: function(transport) {
        if (transport.responseText == " ") {
          clearVideoLookup();
          $("video_youtube_code").addClassName("bad_youtube");
        } else {
          var youtube = transport.responseText.evalJSON();
          if ($("video_title").value == "") $("video_title").value = youtube.title;
          $("video_author").update(youtube.author);
          if ($("video_description").value == "") $("video_description").value = youtube.description;
          $("video_thumbnail").src = youtube.thumbnail;
          $("video_views").update(youtube.views);
          $("video_tags").update(youtube.tags);
          $("video_rating").update(youtube.rating);
          $("video_date").update(youtube.date);
          $("video_length").update(youtube.length);
        }
      }
    });
  } else {
    if (code.length > 0) {
      $("video_youtube_code").addClassName("bad_youtube");
      clearVideoLookup();
    } else {
      $("video_youtube_code").removeClassName("bad_youtube");
    }
  }
}

function clearVideoLookup() {
  $("video_title").value = "";
  $("video_author").update("");
  $("video_description").value = "";
  $("video_thumbnail").src = "";
  $("video_views").update("");
  $("video_tags").update("");
  $("video_rating").update("");
  $("video_date").update("");
  $("video_length").update("");
}

function wallPostClicked(event) {
	wallPost(target(event));
	return false;
}

function wallPost(obj) {
	obj = $(obj);
  $(obj.parentNode);
  msg_obj = obj.previousSiblings()[1];
  var message = prepParams(msg_obj.value);
  var tag = prepParams(obj.previousSiblings()[0].value);
  if (message.length > 0) {
    new Ajax.Request('/posts/create', {
      parameters: "message=" + message +"&tag=" + tag,
      onSuccess: function(transport) {
        obj.parentNode.nextSiblings()[0].insert({top: transport.responseText});
        obj.previousSiblings()[0].value = "";
        new Effect.Highlight(obj.parentNode.nextSiblings()[0].immediateDescendants()[0]);
        if (typeof(fb_template_bundle_wall_post_id) != "undefined" && 
            typeof(FB) != "undefined" && 
            FB.Connect.get_loggedInUser() ) {
              FB.Connect.showFeedDialog(fb_template_bundle_wall_post_id, {"message": msg_obj.value});
              msg_obj.value = "";
            }
        obj.previousSiblings()[0].focus();
        // array(array('text' => 'check out SWN', 'href' => 'http://ec2-1.tbcn.ca:3002')
      }
    });
  }
}

var contest_fields = null;
// var contest_errors = null;
contest_errors = [];

function build_form(id, contest_form) {
	contest_errors = [];
	// set to form-data if we've got a file attachment
	if($$("form#" + id + " input[type='file']").length > 0) { contest_form.writeAttribute('enctype', 'multipart/form-data'); }
	fields(id).each(function(obj) {
    var attributes = contestAttributesHash(obj);
    if (/^fan/i.test(obj.name)) {
			// if name starts with fan
      var name = obj.name.substring(obj.name.indexOf('[') + 1, obj.name.length - 1);
			var new_input_name = 'submit_' + obj.name;
      if (attributes.datatype == "boolean") {
        value = obj.checked ? "1" : "0";
			} else if (attributes.datatype == "radio") {
				checked_input = $$("form#" + id + " input[name='" + obj.name + "']").find(function(radio) { return radio.checked; });
				if(checked_input) {
					value = checked_input.value
				} else {
					value = "";
				}
      } else {
        value = obj.value;
      }
			$$("form#" + id + " input[name='" + new_input_name + "']").each(function(obj) {
				obj.remove();
			});
			appended = contest_form.appendChild(new Element('input', {'type': 'hidden', 'name': new_input_name, 'value': value}));
    } else {
      var name = obj.name.substring(obj.name.indexOf('[') + 1, obj.name.length - 1);
      element_name = "submit_" + obj.name.sub(name, name + "~~~" + attributes.datatype);

      if (attributes.datatype == "boolean") {
        value = obj.checked ? "1" : "0";
      } else {
        value = obj.value;
      }
			$$("form#" + id + " input[name='" + element_name + "']").each(function(obj) {
				obj.remove();
			});
      contest_form.appendChild(new Element('input', {'type': 'hidden', 'name': element_name, 'value': value}));
    }
		
		validate_form_item(obj, name);
  });

}

function highlight_validation_errors(id) {
	fields(id).each(function(obj) {
		var attributes = contestAttributesHash(obj);
    if (/^fan/i.test(obj.name)) { 
			var name = obj.name.substring(obj.name.indexOf('[') + 1, obj.name.length - 1);
		} else {
	  	var name = obj.name.substring(obj.name.indexOf('[') + 1, obj.name.length - 1);
		}
		
		validate_form_item(obj, name);
	});
}

function validate_form_item(obj, name) {
	var attributes = contestAttributesHash(obj);
	
	if (attributes.type != undefined) {
		/* highlighting of field wrapper temporarily removed
		var err_fw_id = 'swn_fw_' + obj.name.replace(/\[|\]/g, '');
		if($(err_fw_id) != null) {
			$(err_fw_id).removeClassName('swn_field_error');	
		}
		*/
		obj.removeClassName('swn_field_error');

		pre_validation_errors_length = contest_errors.length;
    
		if (["string", "hidden", "password"].include(attributes.datatype)) {
      if (attributes.length_range != "") validate_length_range(obj, attributes, name);
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
      if (attributes.pattern != "") validate_pattern(obj, attributes, name);
    }
    if (attributes.datatype == "numeric") {
      if (attributes.numeric == "true") validate_numeric(obj, attributes, name);
      if (attributes.whole == "true") validate_whole(obj, attributes, name);
      if (attributes.range != "") validate_range(obj, attributes, name);
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
    }    
    if (attributes.datatype == "url") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
      if (attributes.url == "true") validate_url(obj, attributes, name);
    }
    if (attributes.datatype == "email") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
      if (attributes.email == "true") validate_email(obj, attributes, name);
    }
    if (attributes.datatype == "youtube") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
      if (attributes.shortcode == "true") validate_shortcode(obj, attributes, name);
    }
    if (attributes.datatype == "date") {
      if (attributes.date_range != "") validate_date_range(obj, attributes, name);
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
    }
    if (attributes.datatype == "list") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
    }
    if (attributes.datatype == "image") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
    }
    if (attributes.datatype == "radio") {
      if (attributes.mandatory == "true") validate_mandatory(obj, attributes, name);
   	}
		
		/* highlighting of field wrapper temporarily removed
		if(pre_validation_errors_length != contest_errors.length) {
			$(err_fw_id).addClassName('swn_field_error');
		}
		*/
		if(pre_validation_errors_length != contest_errors.length) {
			obj.addClassName('swn_field_error');
		}
  }
}

function submitContest(id) {
  // var contest_form = new Element('form', {'method': 'post', 'action': String(document.location)});
	var contest_form = $(id);
  contest_errors = [];

	build_form(id, contest_form);

  if (contest_errors.length == 0 || ignore_form_errors) {
    $(id + "_errors").update("").hide();
    contest_form.appendChild(new Element('input', {'type': 'hidden', 'name': 'submission_type', 'value': 'contest'}));
		$(id).submit();
  } else {
    $(id + "_errors").update(contest_errors.join("<br/>") + "<br/>").show();
  }
}

function submitSignup() {
	var contest_form = $('swn_signup_form');
  contest_errors = [];

	build_form('swn_signup_form', contest_form);

  if (contest_errors.length == 0 || ignore_form_errors) {
		$("swn_signup_form").submit();
  } else {
    $("signup_error").update(contest_errors.join("<br/>") + "<br/>").show();
  }

	return false;
	//build_form('swn_signup_form', $('swn_signup_form')); if(contest_errors == null || contest_errors.empty()){ $('swn_signup_form').submit()};
}

function attributesHash(element) {
  var attributes = {};
  for (i = 0; i < element.attributes.length; i++) {
    attributes[element.attributes[i].nodeName] = element.attributes[i].nodeValue;
  }
  return attributes;
}

function contestAttributesHash(element) {
  var attributes = attributesHash(element);
  if (attributes.length_range == undefined) attributes.length_range = "";
  if (attributes.date_range == undefined) attributes.date_range = "";
  if (attributes.numeric == undefined) attributes.numeric = "false";
  if (attributes.whole == undefined) attributes.whole = "false";
  if (attributes.range == undefined) attributes.range = "";
  if (attributes.mandatory == undefined) attributes.mandatory = "false";
  if (attributes.email == undefined) attributes.email = "false";
  if (attributes.url == undefined) attributes.url = "false";
  if (attributes.shortcode == undefined) attributes.shortcode = "false";
  if (attributes.pattern == undefined) attributes.pattern = "";
  return attributes;
}

function fields(id) {
  if (contest_fields == null) {
    contest_fields = [];
    $$("form#" + id + " input[name^=fan]").each(function(obj) { contest_fields.push(obj); });
    $$("form#" + id + " input[name^=contest]").each(function(obj) { contest_fields.push(obj); });
    $$("form#" + id + " input[name^=image]").each(function(obj) { contest_fields.push(obj); });
    $$("form#" + id + " input[name^=video]").each(function(obj) { contest_fields.push(obj); });
  }
  return contest_fields;
}

function validate_mandatory(obj, attributes, name) {
	if (attributes.datatype == 'radio') {
		if($$("form#" + obj.form.id + " input[name='" + obj.name + "']")[0] == obj) {
			// only check value for the first radio button <input> field for this named group
			checked_input = $$("form#" + obj.form.id + " input[name='" + obj.name + "']").find(function(radio) { return radio.checked; });
			if (checked_input == null) {
				contest_errors.push(name.capitalize() + " is a mandatory field which cannot be omitted.");
			}
		}
	} else {
 		if (obj.value.empty()) { contest_errors.push(name.capitalize() + " is a mandatory field which cannot be omitted."); }
	}
}

function validate_numeric(obj, attributes, name) {
  if (/^[0-9.]*$/.test(obj.value) == false) { contest_errors.push(name.capitalize() + " must be a number."); }
}

function validate_whole(obj, attributes, name) {
  if (parseInt(obj.value) != parseFloat(obj.value) && obj.value != "") { contest_errors.push(name.capitalize() + " must be a whole number with no decimal values."); }
}

function validate_date_range(obj, attributes, name) {
  if (/^([\d]{1,2}\/){2}[\d]{4}-([\d]{1,2}\/){2}[\d]{4}$/.test(attributes.date_range)) {
    var range = attributes.date_range.split("-");
    var date_low = new Date(range[0].split("/")[2], range[0].split("/")[0], range[0].split("/")[1]);
    var date_high = new Date(range[1].split("/")[2], range[1].split("/")[0], range[1].split("/")[1]);
    var low = [date_low.toString().split(" ")[1], date_low.toString().split(" ")[2], date_low.toString().split(" ")[3]].join(" ");
    var high = [date_high.toString().split(" ")[1], date_high.toString().split(" ")[2], date_high.toString().split(" ")[3]].join(" ");
    var date = new Date(obj.value.split("/")[2], obj.value.split("/")[0], obj.value.split("/")[1]);
    if (date < date_low || date > date_high) { contest_errors.push(name.capitalize() + " must be between " + low + " and " + high + "."); }
  }
}

function validate_length_range(obj, attributes, name) {
  if (/^(\d*)-(\d*)$/.test(attributes.length_range)) {
    var range = attributes.length_range.split("-");
    if (obj.value.length < parseInt(range[0]) || obj.value.length > parseInt(range[1])) { contest_errors.push(name.capitalize() + " must be at least " + range[0] + " and no more than " + range[1] + " characters long."); }
  }
}

function validate_range(obj, attributes, name) {
  if (/^(\d*\.?\d+)-(\d*\.?\d+)$/.test(attributes.range)) {
    var range = attributes.range.split("-");
    if (obj.value < parseFloat(range[0]) || obj.value > parseFloat(range[1])) { contest_errors.push(name.capitalize() + " must be between " + range[0] + " and " + range[1] + "."); }
  }
}

function validate_email(obj, attributes, name) {
  if (/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}$/.test(obj.value) == false && obj.value != "") { contest_errors.push(name.capitalize() + " must be a valid email address."); }
}

function validate_url(obj, attributes, name) {
  if (/^((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/i.test(obj.value) == false && obj.value != "") { contest_errors.push(name.capitalize() + " must be a valid URL."); }
}

function validate_shortcode(obj, attributes, name) {
  if (/^[a-zA-Z0-9_-]{11}$/.test(obj.value) == false && obj.value != "") { contest_errors.push(name.capitalize() + " must be a valid Youtube code, which is 11 characters long."); }
}

function validate_pattern(obj, attributes, name) {
  if (new RegExp(attributes.pattern).test(obj.value) == false) { contest_errors.push(name.capitalize() + " is not in the correct format."); }
}

function calcDates(name, set) {
  if (name != undefined) {
    dates = $$("input[date='" + name + "']");
  } else {
    dates = $$("input[date]");
  }
  dates.each(function(obj) {
    attribute = obj.readAttribute("date");
    if (obj.value.empty() || set == true) {
      obj.value = $$("select[input='" + attribute + "_month']")[0].value + "/" + $$("select[input='" + attribute + "_day']")[0].value + "/" + $$("select[input='" + attribute + "_year']")[0].value;
    } else {
      parts = obj.value.split("/");
      $$("select[input='" + attribute + "_month']")[0].value = parseInt(parts[0]);
      $$("select[input='" + attribute + "_day']")[0].value = parseInt(parts[1]);
      $$("select[input='" + attribute + "_year']")[0].value = parseInt(parts[2]);
    }
  });
}

function calcLists(name, set) {
  if (name != undefined) {
    lists = $$("input[list='" + name + "']");
  } else {
    lists = $$("input[list]");
  }
  lists.each(function(obj) {
    attribute = obj.readAttribute("list");
		datatype = obj.readAttribute("datatype");
		
		if(datatype == "list") {
			// <select> type list input
	    if (obj.value.empty() || set == true) {
	      values = [];
	      $$("select[input='" + attribute + "_list']")[0].childElements().each(function(item) {
	        if (item.selected) values.push(item.value);
	      });
	      obj.value = values.join(",");
	      if (obj.value == "") {
	        select = $$("select[input='" + attribute + "_list']")[0];
	        select.childElements()[0].selected = true;
	        obj.value = select.value;
	      }
	    } else {
	      values = obj.value.split(",");
	      $$("select[input='" + attribute + "_list']")[0].childElements().each(function(item) {
	        item.selected = values.include(String(item.value));
	      });

	    }			
		} else if(datatype == "radio") {
			// radio list input
			
		}
  });
}

function submitAgeCheck() {
  if ($('av_province').value != '' && $('av_day').value != '' && $('av_month').value != '' && $('av_year').value != '') {
    var av_form = new Element('form', {'method': 'post', 'action': '/age_check'});
    av_form.appendChild(new Element('input', {'type': 'hidden', 'name': 'province', 'value': $('av_province').value}));
    av_form.appendChild(new Element('input', {'type': 'hidden', 'name': 'day', 'value': $('av_day').value}));
    av_form.appendChild(new Element('input', {'type': 'hidden', 'name': 'month', 'value': $('av_month').value}));
    av_form.appendChild(new Element('input', {'type': 'hidden', 'name': 'year', 'value': $('av_year').value}));
    $('av_error').hide();
    document.body.appendChild(av_form);

		var params = Form.serialize(av_form);
	  new Ajax.Request('/age_check', {
			method: 'post',
			parameters: params,
	    onSuccess: function(transport) {
				if(transport.responseText == "1") {
					$('swn_ageverifyoverlay').hide();
				} else if(transport.responseText == "0") {
					$('av_response_error').show();
					$('av_response_error').innerHTML = $('av_error_text').value;
				} else {
					$('av_response_error').show();
					$('av_response_error').innerHTML = "There was an error processing your age";
				}
	    }
	  });

    // $$('form').last().submit();
  } else {
    $('av_error').show();
  }
}
function moderationAction(id, action, type) {
  new Ajax.Request("/dashboard/moderation_action/" + id, {
    parameters: "activity=" + action + "&resource=" + type + "&notification=" + prepParams($(type + '_notification_' + id).value) + "&badge_id=" + $(type + '_reward_' + id).value,
    onSuccess: function(transport) {
      Effect.Fade(type + "_block_" + id);
    }
  });
}

function checkRegisterCode() {
  new Ajax.Request("/register_from_code", {
    method: "get",
    parameters: "unique_identifier=" + prepParams($('register_unique_identifier').value) + "&email_address=" + prepParams($('register_email_address').value),
    onSuccess: function(transport) {
      if (transport.responseText == " ") {
        $('register_error').show();
      } else {
        pending_user = transport.responseText.split(",");
        $('register_error').hide();
        $('pending_user_token').value = pending_user[0];
        $('pending_user_photo').value = pending_user[1];
        $('PendingPhoto').src = pending_user[1];
        if (pending_user[2] != "") {
          $("swn_pending_badges").update("<br/><strong>Pending Badges</strong><br/>")
          pending_user[2].split("~~~").each(function(obj) {
            badge = obj.split("\\");
            $("swn_pending_badges").update($("swn_pending_badges").innerHTML + "<img src='" + badge[1] + "'/><br/>" + badge[0] + "<br/>");
          });
        }
        $('register_user_email').value = $('register_email_address').value;
        $('swn_signup').show();
        $('swn_signup_code').hide();
        $('register_login').focus();
      }
    }
  });
}

// Button Script
//  http://monc.se/kitchen/59/scalable-css-buttons-using-png-and-background-colors/

var btn = {
    init : function() {
        if (!document.getElementById || !document.createElement || !document.appendChild) return false;
        as = btn.getElementsByClassName('btn(.*)');
        for (i=0; i<as.length; i++) {
            if ( as[i].tagName == "INPUT" && ( as[i].type.toLowerCase() == "submit" || as[i].type.toLowerCase() == "button" ) ) {
                var a1 = document.createElement("a");
                a1.appendChild(document.createTextNode(as[i].value));
                a1.className = as[i].className;
                a1.id = as[i].id;
                as[i] = as[i].parentNode.replaceChild(a1, as[i]);
                as[i] = a1;
                as[i].style.cursor = "pointer";
            }
            else if (as[i].tagName == "A") {
                var tt = as[i].childNodes;
            }
            else { return false };
            var i1 = document.createElement('i');
            var i2 = document.createElement('i');
            var s1 = document.createElement('span');
            var s2 = document.createElement('span');
            s1.appendChild(i1);
            s1.appendChild(s2);
            while (as[i].firstChild) {
              s1.appendChild(as[i].firstChild);
            }
            as[i].appendChild(s1);
            as[i] = as[i].insertBefore(i2, s1);
        }
        // The following lines submits the form if the button id is "submit_btn"
        btn.addEvent(document.getElementById('submit_btn'),'click',function() {
            var form = btn.findForm(this);
            form.submit();
        });
        // The following lines resets the form if the button id is "reset_btn"
        btn.addEvent(document.getElementById('reset_btn'),'click',function() {
            var form = btn.findForm(this);
            form.reset();
        });
    },
    findForm : function(f) {
        while(f.tagName != "FORM") {
            f = f.parentNode;
        }
        return f;
    },
    addEvent : function(obj, type, fn) {
      if (obj) {
        if (obj.addEventListener) {
            obj.addEventListener(type, fn, false);
        }
        else if (obj.attachEvent) {
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
            obj.attachEvent("on"+type, obj[type+fn]);
        }
      }
    },
    getElementsByClassName : function(className, tag, elm) {
        var testClass = new RegExp("(^|\s)" + className + "(\s|$)");
        var tag = tag || "*";
        var elm = elm || document;
        var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
        var returnElements = [];
        var current;
        var length = elements.length;
        for(var i=0; i<length; i++){
            current = elements[i];
            if(testClass.test(current.className)){
                returnElements.push(current);
            }
        }
        return returnElements;
    }
}

btn.addEvent(window,'load', function() { btn.init();} );

/**
 * @author Ryan Johnson <ryan@livepipe.net>
 * @copyright 2007 LivePipe LLC
 * @package Control.Tabs
 * @license MIT
 * @url http://livepipe.net/projects/control_tabs/
 * @version 2.1.1
 */

if(typeof(Control) == 'undefined')
	var Control = {};
Control.Tabs = Class.create();
Object.extend(Control.Tabs,{
	instances: [],
	findByTabId: function(id){
		return Control.Tabs.instances.find(function(tab){
			return tab.links.find(function(link){
				return link.key == id;
			});
		});
	}
});
Object.extend(Control.Tabs.prototype,{
	initialize: function(tab_list_container,options){
		this.activeContainer = false;
		this.activeLink = false;
		this.containers = $H({});
		this.links = [];
		Control.Tabs.instances.push(this);
		this.options = {
			beforeChange: Prototype.emptyFunction,
			afterChange: Prototype.emptyFunction,
			hover: false,
			linkSelector: 'li a',
			setClassOnContainer: false,
			activeClassName: 'active',
			defaultTab: 'first',
			autoLinkExternal: true,
			targetRegExp: /#(.+)$/,
			showFunction: Element.show,
			hideFunction: Element.hide
		};
		Object.extend(this.options,options || {});
		(typeof(this.options.linkSelector == 'string')
			? $(tab_list_container).getElementsBySelector(this.options.linkSelector)
			: this.options.linkSelector($(tab_list_container))
		).findAll(function(link){
			return (/^#/).exec(link.href.replace(window.location.href.split('#')[0],''));
		}).each(function(link){
			this.addTab(link);
		}.bind(this));
		this.containers.values().each(this.options.hideFunction);
		if(this.options.defaultTab == 'first')
			this.setActiveTab(this.links.first());
		else if(this.options.defaultTab == 'last')
			this.setActiveTab(this.links.last());
		else
			this.setActiveTab(this.options.defaultTab);
		var targets = this.options.targetRegExp.exec(window.location);
		if(targets && targets[1]){
			targets[1].split(',').each(function(target){
				this.links.each(function(target,link){
					if(link.key == target){
						this.setActiveTab(link);
						throw $break;
					}
				}.bind(this,target));
			}.bind(this));
		}
		if(this.options.autoLinkExternal){
			$A(document.getElementsByTagName('a')).each(function(a){
				if(!this.links.include(a)){
					var clean_href = a.href.replace(window.location.href.split('#')[0],'');
					if(clean_href.substring(0,1) == '#'){
						if(this.containers.keys().include(clean_href.substring(1))){
							$(a).observe('click',function(event,clean_href){
								this.setActiveTab(clean_href.substring(1));
							}.bindAsEventListener(this,clean_href));
						}
					}
				}
			}.bind(this));
		}
	},
	addTab: function(link){
		this.links.push(link);
		link.key = link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
		this.containers[link.key] = $(link.key);
		link[this.options.hover ? 'onmouseover' : 'onclick'] = function(link){
			if(window.event)
				Event.stop(window.event);
			this.setActiveTab(link);
			return false;
		}.bind(this,link);
	},
	setActiveTab: function(link){
		if(!link)
			return;
		if(typeof(link) == 'string'){
			this.links.each(function(_link){
				if(_link.key == link){
					this.setActiveTab(_link);
					throw $break;
				}
			}.bind(this));
		}else{
			this.notify('beforeChange',this.activeContainer);
			if(this.activeContainer)
				this.options.hideFunction(this.activeContainer);
			this.links.each(function(item){
				(this.options.setClassOnContainer ? $(item.parentNode) : item).removeClassName(this.options.activeClassName);
			}.bind(this));
			(this.options.setClassOnContainer ? $(link.parentNode) : link).addClassName(this.options.activeClassName);
			this.activeContainer = this.containers[link.key];
			this.activeLink = link;
			this.options.showFunction(this.containers[link.key]);
			this.notify('afterChange',this.containers[link.key]);
		}
	},
	next: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i + 1]){
				this.setActiveTab(this.links[i + 1]);
				throw $break;
			}
		}.bind(this));
		return false;
	},
	previous: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i - 1]){
				this.setActiveTab(this.links[i - 1]);
				throw $break;
			}
		}.bind(this));
		return false;
	},
	first: function(){
		this.setActiveTab(this.links.first());
		return false;
	},
	last: function(){
		this.setActiveTab(this.links.last());
		return false;
	},
	notify: function(event_name){
		try{
			if(this.options[event_name])
				return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
		}catch(e){
			if(e != $break)
				throw e;
			else
				return false;
		}
	}
});
if(typeof(Object.Event) != 'undefined')
	Object.Event.extend(Control.Tabs);


function addStandardMessage() {
	$("standard_messages").insert("<li><p><textarea name=\"new_messages[]\"></textarea></p></li>");
}

function deleteStandardMessage(target) {
	console.log($(target).up("li").remove());
}

function referStandardMessageChanged(target) {
	$("refer_message").value = target.value.replace(/\\n/g, '\n').replace(/\\/,'');
}


/* Facebook Connect Related */
function facebook_login_button_click() {
  FB.Facebook.get_sessionState().waitUntilReady(function() {
    window.location.reload(true);
  });
}

function hashItems() {
  var items = new Object();

  hash_items = location.hash.replace(/^#/, '').split('/');
  for(i = 0; i < hash_items.length; i++){
    key_val = hash_items[i].split('=');
    items[key_val[0]] = key_val[1];
  }
  return items;
}

function hashItemsToString(hash_items) {
  var str = '';
  for(i in hash_items) {
    str = str + i + '=' + hash_items[i] + '/';
  }
  return str;
}

function setAjaxUrlRef(key, value) {
  hash_items = hashItems();
  hash_items[key] = value;
  location.hash = hashItemsToString(hash_items);
  // setHashOnAllLinksToSelf();
}

function setHashOnAllLinksToSelf() {
  page_match = /^(http:\/\/[^\/]*\/[^\/|#]*)/.exec(location.href);
  page_link = page_match[1]
  $$('a').each(function(anchor_tag) {
    if(anchor_tag.href.startsWith(page_link)) {
      link_match = /(^.*[^|#]*)/.exec(anchor_tag.href);
      new_link = link_match[1] + location.hash;
      anchor_tag.href = new_link;
    }
  });
}

function getAjaxUrlRef(key) {
  return hashItems()[key];
}

function processHashes() {
  setHashOnAllLinksToSelf();
  hash_items = hashItems();
  
  for(i in hash_items) {
    if(typeof i != "undefined") {
      fn = i + 'load_page';
      eval('if(typeof ' + fn + '!= "undefined"){ ' + fn + '(' + hash_items[i] + ');}');
    }
  }
}

function mapHtmlElementId(id) {
  for(key in html_elements_map) {
    id = id.replace(key, html_elements_map[key])
  }

  return id;
}

var query_string_items = {};

function setSelfLinkingQeuryStringVal(key, value) {
  // key = mapHtmlElementId(key);
  // query_string_items = queryStringItems();
  queryStringItems()[key] = value;
  
  updateQueryStringOnLinksToSelf();
}

function updateQueryStringOnLinksToSelf() {
  page_match = /^(http:\/\/[^\/]*\/[^\/|#|\?]*)/.exec(location.href);  // match swn page URL without query string or hash string
  fr_page_match = /^(http:\/\/[^\/]*\/fr\/[^\/|#|\?]*)/.exec(location.href);
  en_page_match = /^(http:\/\/[^\/]*\/en\/[^\/|#|\?]*)/.exec(location.href);
  page_link = null;
  if(page_match != null) {
    page_link = page_match[1];
  } else if (en_page_match != null){
    en_page_link = en_page_match[1];
  } else if (fr_page_match != null){
    fr_page_link = fr_page_match[1];
  }

  if(page_link != null) {
    $$('a').each(function(anchor_tag) {
      if(anchor_tag.ancestors()[0].hasClassName('pagination')) {
        // return; // ignore pagination methods - was breaking non-ajax pagination methods
      }
      if(anchor_tag.href.startsWith(page_link)) {
        url_match = /^(http:\/\/[^#|\?]*)/.exec(anchor_tag.href); // match url without query string or hash string

        url = url_match[1];
        q_items = new queryStringItems();//.clone(queryStringItems());
        if(location.href.include('?')) {
          Object.extend(q_items, Object.clone(queryStringItems()));
        }

        if(anchor_tag.href.include('?')) {
          anchor_tag_items = anchor_tag.href.toQueryParams();
          Object.extend(anchor_tag_items, q_items);
          q_items = anchor_tag_items;
        }

        new_link = url + itemsToQueryString(q_items) + anchor_tag.hash;
        anchor_tag.href = new_link;
      }
    });
  }

}

function itemsToQueryString(items) {
  str = "?";
  //for(i in items) {
  //  str = str + i + "=" + items[i] + "&"
  //}
  str = str + Object.toQueryString(items);
  // str = str.replace(/&$/, '');
  str = str.replace(/^\?$$/, '');
  return str;
}

function getQeuryStringVal(key) {
  return queryStringItems()[key];
}

function queryStringItems() {
  
  if(query_string_items == null) {
    if(location.href.include('?')) {
      query_string_items = location.href.toQueryParams();
    } else {
      query_string_items = new Object();
    }
  }
  return query_string_items;
}

function fbRequireSession() {
  FB.Connect.requireSession(function() {window.location.reload(true);});
  if($$('.fb_tosIFrame').size() > 0 && $$('.fb_tosIFrame')[0].getStyle('height') == '340px') {
    setTimeout("$$('.fb_tosIFrame')[0].setStyle({height: '370px'})", 1000);
  }
}

function submitParentForm(src) {
  f = src;
  while(f.tagName != "FORM") {
    f = f.parentNode;
  }

  f.submit();
}

function share_template_on_facebook(template_id, data) {
  if (data === undefined) { data = {}; }
  if (data["image_url"]) {
    data["images"] = [{"src": data["image_url"], "href": data["page_url"]}]
  }
  FB.Connect.showFeedDialog(template_id, data, [], null, null, FB.RequireConnect.promptConnect);
  return false;
}

function tweetify_textarea(selector) {
  $$(selector).each(function(t) {
    t.addClassName('tweet-text');
    t.insert({before:"<div class='tweet-info'>" + (140 - t.value.length) + "</div>"});
    t.observe('keydown',function(e) {
      if (t.value.length > 140)
        t.value = t.value.substr(0,140);
    });
    t.observe('keyup',function(e) {
      var t = Event.element(e);
      if (t.value.length > 140)
        t.value = t.value.substr(0,140);
      t.adjacent('.tweet-info')[0].innerHTML = (140 - t.value.length);
    });
  });
}

// var row_template = new Template('<tr><td>#{city}</td><td>#{province}</td><td>#{date}</td><td>#{location}</td><td>#{time}</td></tr>');

// $$('.swn_content')[0].insert({top: "<table id='data_table'><tr><td>hi</td></tr></table>"});
// $$('#data_table tr:last')[0].insert({after: "<tr><td>hi2</td></tr>"});

// $A(table_data).each( function(item) { console.log(item[2]); });
// row_template.evaluate({city: item[0], province: item[1], date: item[2], location: item[3], time: "2pm"})

//$A(table_data).each( function(item) { $$('#data_table tr:last')[0].insert({after:    row_template.evaluate({city: item[0], province: item[1], date: item[2], location: item[3], time: "2pm"})    }); });


