

/****************************/
/*		FORM SUBMISSIONS	*/
/****************************/

// Child Finder
function submitChildFind() {
	var lang = document.getElementById('findLang').value;
				
	var age = document.getElementById("findAge");
	age = age.options[age.selectedIndex].value;
				
	var gender = document.getElementById("findGender");
	gender = gender.options[gender .selectedIndex].value;
				
	var country = document.getElementById("findCountry");
	country = country.options[country.selectedIndex].value;
				
	document.location.href = "https://children.worldvision.ca/Sponsorship/Forms/Child.aspx?lang="+lang+"&gender="+gender+"&age="+age+"&country="+country+"&mc=4265948";
}

// Search Box
function searchSubmit() {
	var term = document.getElementById("searchBox").value;

	document.location.href = "/Pages/SearchResults.aspx?k="+term;
}

// Donor Login
function login() {
	var path="https://auth.worldvision.ca/adfs/ls/auth/forms/WvcLogin.aspx?wa=wsignin1.0&amp;wreply=https%3a%2f%2flogin.worldvision.ca%2fmemberssecure%2f&amp;wct=2010-08-04T15%3a35%3a10Z&amp;wctx=https%3a%2f%2flogin.worldvision.ca%2fmemberssecure%2fForms%2fLanding.aspx";
				w
	var username = document.getElementById("username").value;
				
	var password = document.getElementById("password").value;
				
	// CREATE THE FORM
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", path);

	// ADD THE USERNAME FIELD
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "ctl00_dmtBorderBodyContent_txtUserName");
    hiddenField.setAttribute("value", username);

    form.appendChild(hiddenField);
    
    // ADD THE PASSWORD FIELD
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "ctl00_dmtBorderBodyContent_txtPassword");
    hiddenField.setAttribute("value", password);

    form.appendChild(hiddenField);

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}


/****************************/
/*	CHILD SELECTOR WIDGET	*/
/****************************/
function updatewvc(searchResult) {
    if(searchResult.Message == null) {
        document.getElementById("wvcsw_message").innerHTML = "";
    } else {
        document.getElementById("wvcsw_message").innerHTML = searchResult.Message;
    } 
    var child = searchResult.Children[0];

	document.getElementById("wvcsw_image").innerHTML = "<img src='" + child.ImageUrl + "' style='height:200px;width:150px;border-width:0px;'''>";
	var childName = child.FirstName;
	var endChar = childName.indexOf(" ");
	if (endChar == -1) {	
		document.getElementById("wvcsw_child_name").innerHTML = "My name is "+child.FirstName;
	} else {
		childName = childName.substring(0,endChar);
		document.getElementById("wvcsw_child_name").innerHTML = "My name is "+childName;
	}
	
	document.getElementById("wvcsw_child_id").value = child.Id;

}

function callwebServiceSearch() {
    var parameter = "noc=" +  WVCSponsorWidget.noc + "&lang=" + WVCSponsorWidget.lang;
    var type = $("#wvcsw_ddlType").val();
    $.wvcSWSearch(parameter, updatewvc);
}

function sponsorNow() {
    window.location = WVCSponsorWidget.SponsorshipURL + "?mc=3800331&asc=" + document.getElementById("wvcsw_child_id").value;
}


/****************************/
/*		JQuery Functions	*/
/****************************/
$(document).ready(function(){
	
	/****************************/
	/*	TWITTER FEED PARSING	*/
	/****************************/
	/*
		$.getJSON('http://twitter.com/status/user_timeline/worldvisioncan.json?count=2&include_entities=true&callback=?', function(data){
	//$.getJSON('http://twitter.com/status/user_timeline/wvcanadanews.json?count=2&callback=?', function(data){


	$('.loading').replaceWith('');
		$.each(data, function(index, item){
		
			$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '<strong> - ' + relative_time(item.created_at) + '</strong></p></div>');
		});
	});
	
	// Calculate Readable Time
	function relative_time(time_value) {
		var values = time_value.split(" ");
	  	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  	var parsed_date = Date.parse(time_value);
	  	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  	delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  	var r = '';
	  	if (delta < 60) {
			r = 'a minute ago';
	  	} else if(delta < 120) {
			r = 'couple of minutes ago';
	  	} else if(delta < (45*60)) {
			r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  	} else if(delta < (90*60)) {
			r = 'an hour ago';
	  	} else if(delta < (24*60*60)) {
			r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  	} else if(delta < (48*60*60)) {
			r = '1 day ago';
	  	} else {
			r = (parseInt(delta / 86400)).toString() + ' days ago';
	  	}
	  
	  return r;
	}
	
	// Re-Write incomplete links
	String.prototype.linkify = function (){
        text = this.replace(
            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">(link)</a>';
            }
        );
		
		// LINK SEARCH HASH
		text = text.replace(
            /((#))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w!:.?+=&%!\-\/]))?/gi,
            function(url){
                    full_url = 'http://www.twitter.com/search?q=%23' + url.substring(1,url.length);
                return '#<a href="' + full_url + '" target="_blank">' + url.substring(1,url.length) + '</a>';
            }
        );
		
		// LINK USERS 
		text = text.replace(
            /((@))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w!:.?+=&%@!\-\/]))?/gi,
            function(url){
                    full_url = 'http://www.twitter.com/' + url.substring(1,url.length);
                return '@<a href="' + full_url + '" target="_blank">' + url.substring(1,url.length) + '</a>';
            }
        );
		
    	return text;
	}
	*/
	/****************************/
	/*	Initiate Child Selector	*/
	/****************************/
	
	setTimeout("if($('#wvcsw_box1_div').length > 0) {$.wvcSWSearch(null, updatewvc)}",100);
	/****************************/
	/*	  Lightbox Triggers	    */
	/****************************/
	$("#lb_btn_1").click(function(){
		currentDiv = "#lb_1";
		centerPopup(currentDiv);
		return false;
	});
	
	$("#lb_btn_2").click(function(){
		currentDiv = "#lb_2";
		centerPopup(currentDiv);
		return false;
	});

	$("#lb_btn_3").click(function(){
		currentDiv = "#lb_3";
		centerPopup(currentDiv);
		return false;
	});

	$("#lb_btn_4").click(function(){
		currentDiv = "#lb_4";
		centerPopup(currentDiv);
		return false;
	});
	
	$("#lb_btn_5").click(function(){
		currentDiv = "#lb_5";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_6").click(function(){
		currentDiv = "#lb_6";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_7").click(function(){
		currentDiv = "#lb_7";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_8").click(function(){
		currentDiv = "#lb_8";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_9").click(function(){
		currentDiv = "#lb_9";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_1b").click(function(){
		currentDiv = "#lb_1";
		centerPopup(currentDiv);
	});
	
	$("#lb_btn_2b").click(function(){
		currentDiv = "#lb_2";
		centerPopup(currentDiv);
	});

	$("#lb_btn_3b").click(function(){
		currentDiv = "#lb_3";
		centerPopup(currentDiv);
	});

	$("#lb_btn_4b").click(function(){
		currentDiv = "#lb_4";
		centerPopup(currentDiv);
	});


	//	Close Popup (Close button, Background, Escape Key)
	$("#closeButton").click(function(){
		disablePopup();
	});
	
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();	
		}
	});
	
});

/*****************************/
/* Mainspot slide-out Config */
/*****************************/
$(function(){
	if ($('.slide-out-div').length >0) {
	$('.slide-out-div').tabSlideOut({
		positioning: 'relative',
		tabLocation: 'left',                      //side of screen where tab lives, top, right, bottom, or left
		speed: 200,                               //speed of animation
		action: 'click',                          //options: 'click' or 'hover', action to trigger animation
		topPos: '0px',                          //position from the top/ use if tabLocation is left or right
		leftPos: '0px',                          //position from left/ use if tabLocation is bottom or top
		fixedPosition: false,                      //options: true makes it stick(fixed position) on scroll
		onLoadSlideOut: true         
	});
	}
	if ($('.slide-out-extension').length >0) {
	$('.slide-out-extension').tabSlideOut({
		positioning: 'relative',
		tabLocation: 'left',                      //side of screen where tab lives, top, right, bottom, or left
		speed: 600,                               //speed of animation
		action: 'click',                          //options: 'click' or 'hover', action to trigger animation
		topPos: '0px',                          //position from the top/ use if tabLocation is left or right
		leftPos: '0px',                          //position from left/ use if tabLocation is bottom or top
		fixedPosition: false,                      //options: true makes it stick(fixed position) on scroll
		onLoadSlideOut: true         
	});
	}
	$('.slide-out-div').css("display", "block");
	$('.slide-out-extension').css("display", "block");

});

/*****************************/
/*	  Lightbox Functions	 */
/*****************************/
var currentDiv;

function disablePopup(){
		$("#backgroundPopup").animate({"opacity":0}, function(){
			$(this).hide();
		});

		$(currentDiv).animate({"opacity":0}, function(){
			$(this).html($(this).html()).hide();
		});
		$("#closeButton").animate({"opacity":0}, function(){
			$(this).hide();
		});
}

function loadPopup(mydiv){
		$("#backgroundPopup").animate({"opacity":.3});
		$("#closeButton").animate({"opacity":1});
		$(mydiv).animate({"opacity":1});
	window.scroll(0,0);
}

function centerPopup(myDiv){
	var windowWidth = $(document).width();
	var windowHeight = $(document).height();
	var popupHeight = $(myDiv).height();
	var popupWidth = $(myDiv).width();

	$(myDiv).css({
		"position": "absolute",
		"top": 100,
		"left": "50%",
		"marginLeft": -popupWidth/2,
		"display":"block",
		"opacity":0
	});
	
	$('#closeButton').css({
		"position": "absolute",
		"top": 106,
		"left": "50%",
		"marginLeft": popupWidth/2+16,
		"display":"block",
		"opacity":0
	});

	$('#backgroundPopup').css({
		"display":"block",
		"opacity":0
	}).height($(document).height());
	
	loadPopup(myDiv);
}

// DISABLE RIGHT CLICK
function clickIE4(){
if (event.button==2){alert(message);return false;}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){alert(message);return false;}
}
}

if (document.layers){document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS4;
} else if (document.all&&!document.getElementById){ document.onmousedown=clickIE4;}
document.oncontextmenu=new Function("return false")


// MOTCODE Processing
$(function(){
				function isInteger(s) {
				  return (s.toString().search(/^-?[0-9]+$/) == 0);
				}

				var name = "mc";
				var regexS = "[\\?&]mc=([^&#]*)";
				var regex = new RegExp( regexS );
				var results = regex.exec( window.location.href );
				if( results != null ) {
					
					$.each($('#x-slider a[href*="mc"]'), function(){
						mc = results[1];
						if ($(this).attr("href").indexOf("mc=") > -1){
							var replaceText = $(this).attr("href").substring($(this).attr("href").indexOf("mc="));
							var lastChar = replaceText.length;
							for (var i=3;i<replaceText.length;i++){
								if(isInteger(replaceText.charAt(i))) {
									lastChar = i+1;
								}
							}							
							replaceText = replaceText.substring(0, lastChar);
							mc = "mc="+mc;
						} else if ($(this).attr("href").indexOf("mc-") > -1) {
							var replaceText = $(this).attr("href").substring($(this).attr("href").indexOf("mc-"));
							var lastChar = replaceText.length;
							for (var i=3;i<replaceText.length;i++){
								if(isInteger(replaceText.charAt(i))) {
									lastChar = i+1;
								}
							}
							replaceText = replaceText.substring(0, lastChar);
							mc = "mc-"+mc;
						}
						
						var newlink = $(this).attr("href").replace(replaceText, mc);
						$(this).attr("href", newlink);
					});
				}				
});


