var options = { 
	dataType:  'json', 
	beforeSubmit:  validate,  // pre-submit callback 
	success:       processResponse  // post-submit callback 
}; 
var testimonialTarget = "_self";//"_blank";
	 
$(function(){

	$("li :input").focus(function(){
		$(this).parents("li:first").addClass("highlighted");
		//$(this).addClass("highlight");
	});
	$("li :input").blur(function(){
		$(this).parents("li:first").removeClass("highlighted");
	});

	$("#tempoplay_winners").click(function(){
		var link = $("#btn_winners_link");
		window.open(link.attr("href"), testimonialTarget);
		return false;
	});
	$('#tempoplay_winners').hover(function() {
		$(this).css('cursor','pointer');
	}, function() {
		$(this).css('cursor','auto');
	});
	$.preloadCssImages();
});
function initHomeBindings()
{
	/* begin home */
	testimonialTarget = "_self";
	$("#tempoForm #msisdn, #tempoForm #code").focus(function(){
		$(".errormsg").hide();
	});
	$(".errormsg").click(function(){$(this).hide()});
	$("#tempoForm").submit(function(){
		$("#msisdn_error").hide();
		$("#code_error").hide();
		var misdnValue = $("#tempoForm #msisdn").val(); 
	    var codeValue = $("#tempoForm #code").val(); 
		misdnValue = normalizeMSISDN(misdnValue, "be");
		if (misdnValue=="")
		{	
			$("#msisdn_error").show();
			$("#msisdn_error .innererrormess").text(er_invalidMsisdn);
			return false;
		}
		codeValue = codeValue.replace(/[^a-zA-Z0-9\s]/g,'');
		//if (codeValue.length != 10 || value.length != 15)
		if (codeValue.length < 10)
		{
			//alert(codeValue.length + " - " + codeValue);
			$("#code_error").show();
			$("#code_error .innererrormess").text(er_invalidCode);
			return false;
		}
		//alert('true');
	});
	$("#btn_reload_link").click(function(){trackGAEvent("btn_reload_link", "click", "");});
	$("#btn_order_link").click(function(){trackGAEvent("btn_order_link", "click", "");});
	$("#btn_winners_link").click(function(){trackGAEvent("btn_winners_link", "click", "");});
	
/* end home */
}	
/* begin registration */
	
function initRegisterBindings()
{ 
	$("#secondform").hide();
	$("#backForm").click(function(){
		$("#secondform").addClass("hidden");
		$("#firstform").removeClass("hidden");
		$("#firstform").fadeIn("fast");
		$('form li').removeClass("error");
		$("#errormessage").hide();
	});
	if (echeck($.trim($("#el_EMAIL_1").val())) && $.trim($("#el_EMAIL_1").val()) == $.trim($("#el_EMAIL_2").val()))
	{
		$("#el_EMAIL_2").parents("li:first").fadeOut();
	}
	$("#el_EMAIL_1").focus(function(){
		$("#el_EMAIL_2").parents("li:first").fadeIn();
	});
	$("#next").click(function () {
		var result = true;
		$('form li').removeClass("error");
		$("#errormessage").hide();
		$('input.p1required').each(function(){
			var value = $(this).fieldValue(); 
			if (!value[0]){
				$(this).parents("li:first").addClass("error");
				$("#errormessage").show();
				$("#errormessage").text(er_required);
				result = false;
			}
		});
		if (!echeck($.trim($("#el_EMAIL_1").val())))
		{
			$("#el_EMAIL_1").parents("li:first").addClass("error");
			$("#el_EMAIL_2").parents("li:first").addClass("error");
			$("#errormessage").show();
			$("#errormessage").text(er_emailinvalid);
			result = false;
		}
		if ($.trim($("#el_EMAIL_1").val()) != $.trim($("#el_EMAIL_2").val()))
		{
			$("#el_EMAIL_1").parents("li:first").addClass("error");
			$("#el_EMAIL_2").parents("li:first").addClass("error");
			$("#errormessage").show();
			$("#errormessage").text(er_emailnomatch);
			result = false;
		}
		if (result)
		{
			$("#firstform").addClass("hidden");
			$("#secondform").removeClass("hidden");
			$("#secondform").fadeIn("fast");
		}
		return false;
	});
	
	$("#saveForm").click(function(){
	
	});
	//TP_reg_form
	$("#TP_reg_form").submit(function(){
		var result = true;
		$('form li').removeClass("error");
		$('input.p1required').each(function(){
			var value = $(this).fieldValue(); 
			if (!value[0]){
				$(this).parents("li:first").addClass("error");
				$("#secondform").addClass("hidden");
				$("#firstform").fadeIn("fast");
				$("#errormessage").show();
				$("#errormessage").text(er_required);
				result = false;
			}
		});
		if (!echeck($.trim($("#el_EMAIL_1").val())))
		{
			$("#el_EMAIL_1").parents("li:first").addClass("error");
			$("#el_EMAIL_2").parents("li:first").addClass("error");
			$("#secondform").addClass("hidden");
			$("#firstform").fadeIn("fast");
			$("#errormessage").show();
			$("#errormessage").text(er_emailinvalid);
			result = false;
		}
		if ($.trim($("#el_EMAIL_1").val()) != $.trim($("#el_EMAIL_2").val()))
		{
			$("#el_EMAIL_1").parents("li:first").addClass("error");
			$("#el_EMAIL_2").parents("li:first").addClass("error");
			$("#secondform").addClass("hidden");
			$("#firstform").fadeIn("fast");
			$("#errormessage").show();
			$("#errormessage").text(er_emailnomatch);
			result = false;
		}
		$('input.p2required').each(function(){
			var value = $(this).fieldValue(); 
			if (!value[0]){
				$(this).parents("li:first").addClass("error");
				result = false;
			}
		});
		//alert(result);
		return result; 
	});
	
	//ui-autocomplete
	var cache = {}, lastXhr;
	$( ".autostreet" ).autocomplete({		
		source: function( request, response ) {
				var path = "http://www.tempoplay.be/service_road65.php";
				if (document.location.hostname.indexOf("mobistar.be") != -1) path = "http://partners.mobistar.be/tempoplay/service_road65.php";
				else path = "http://" + document.location.hostname + "/service_road65.php";
				$.ajax({ 
					type: "GET",
					url: path,
					dataType: "xml",
					data: {
						postcode: $("#el_adres_4").val(), 
						maxRows: 10,
						street: request.term
					},
					success: function( xmlResponse ) {
						response($( "row", xmlResponse ).map(function() {
							return {
								value: ( $.trim( $(this ).attr("streetname") ) || "(onbekende straat)" ),
								id: $(this ).attr("street_id")
							};
						}));
					}
				});
			},
		minLength: 2,
		select: function( event, ui ) {
			$("#el_street_id").val(ui.item.id);
		}
	});
	$( ".autocity" ).autocomplete({
		source: function( request, response ) {
				var path = "http://www.tempoplay.be/service_road65.php";
				if (document.location.hostname.indexOf("mobistar.be") != -1) path = "http://partners.mobistar.be/tempoplay/service_road65.php";
				else path = "http://" + document.location.hostname + "/service_road65.php";
				$.ajax({
					type: "GET",
					url: path,
					dataType: "xml",
					data: {
						maxRows: 10,
						postcode: request.term
					},
					success: function( xmlResponse ) {
						response($( "row", xmlResponse ).map(function() {
							return {
								value: ( $.trim( $(this ).attr("zipcode") + " - " + $(this ).attr("cityname") ) || "(onbekende straat)" ),
								id: $(this ).attr("city_id")
							};
						}));
					}
				});
			},
		minLength: 2,
		select: function( event, ui ) {
			$("#el_adres_4").val(extractFirst(ui.item.value));
			$("#el_adres_5").val(extractLast(ui.item.value));
			$("#el_city_id").val(ui.item.id);
			return false;
		}
	});
	
}	
	
/* end registration */

/* begin bonuschoise */
function initBonusBindings()
{
	$("#bonus-nav li .choise").click(function(){
		$("#el_CHOISE").val($(this).attr("rel"));
		$("#telcoform1").submit();
		return false;
	});	
}	

/* end bonuschoise */
function initBonusthanksBindings(){}
function initPrizewinBindings(){}
function initAllwinnersBindings(){}
function initPrizesBindings(){}

/* testimonials */
var carpos = ["0", "-960", "-1920", "-2880"];
var curpos = 0;
var interval = 0;
function gotoNextElientje()
{
	if (document.body.className != 'blurred')
	{
		curpos++;
		curpos = curpos > 2 ? 0 : curpos;	
		$("#testimonial-carousel ul").animate({"left": carpos[curpos] + "px"}, "slow");	
		var idpos = curpos + 1;	
		$(".carchooser").removeClass("activecar");
		$("#prijs" + idpos).addClass("activecar");
	}
}

function onBlur() {
    document.body.className = 'blurred'; clearInterval(interval);
};
function onFocus(){
    document.body.className = 'focused'; interval = setInterval("gotoNextElientje()", 12000);
};

function initTestimonialsBindings()
{	if (/*@cc_on!@*/false) { // check for Internet Explorer
		document.onfocusin = onFocus;
		document.onfocusout = onBlur;
	} else {
		window.onfocus = onFocus;
		window.onblur = onBlur;
	}
	//interval = setInterval("gotoNextElientje()", 12000);

	$(".carchooser").click(function(){
		var id = $(this).attr("id");
		var pos = id.substring(id.length - 1);		
		pos--;		
		$("#testimonial-carousel ul").animate({"left": carpos[pos] + "px"}, "slow");
		clearInterval(interval);		
		$(".carchooser").removeClass("activecar");
		$(this).addClass("activecar");
	});

	$("#arrows #prijs4").click(function(){
	  $("#testimonial-carousel ul").animate({"left": carpos[3] + "px"}, "slow");
		clearInterval(interval);
	});

	$("#arrows a").click(function(){
	  $("#arrows a").removeClass("active");
	  $(this).addClass("active");
	});
	
	$(".pagerContainer a").click(function(){
		var page = $(this).attr('href').replace("#", ".");
		var container = '.' + $(this).attr('rel');
		if (!$(this).hasClass('active'))
		{
			$(this).siblings().removeClass('active');
			$(this).addClass('active');
			var len = $(container).length;
			$(container).fadeOut('fast', function() {
				if(--len==1) 
				{
					$(container).hide();
					$(page).fadeIn('fast');
				}
			});
		}
		return false;
	});
	
	/*$(".pagerContainer a").click(function(){
			var page = $(this).attr('href').replace("#", ".");
			var container = '.' + $(this).attr('rel');
			if (!$(this).hasClass('active'))
			{
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
				var len = $(container).length;
				$(container).fadeOut('fast', function() {
					if(--len==1) 
					{
						$(container).hide();
						$(page).fadeIn('fast');
					}
				});
			}
			return false;
		});*/
};

function initPrizethanksBindings(){}
/* helper functions */
function normalizeMSISDN(ovalue, country)
{
	value = ovalue.replace(/[^0-9]/g,'');  
	//this.value = this.value.replace(/[^0-9\s]/g,'');
	//alert('normalize ' + ovalue + ' : result: ' + value);
	if(country.toLowerCase()=="nl")
	{
		//31 - Dutch mobile phone numbers consist of 9 digits also, They start with 06, followed by 8 digits? f* wikipedia / 9 of 10 dus
		if (value.substr(0,4)=="0031")
			value = value.substr(2);
		else if (value.substr(0,3)=="031")
			value = value.substr(1);
		else if (value.substr(0,2)=="31")
			value = value;
		else if (value.substr(0,2)=="06")
			value = "31" + value.substr(1);
		if (value.length != 10 || value.length != 11)
			value = "";	
	}
	else if (country.toLowerCase()=="de")
	{
		//49 - Mobile Phones +49 172 173 17 15 16  The numbers have a total length of ten or eleven digits
		if (value.substr(0,4)=="0049")
			value = value.substr(2);
		else if (value.substr(0,3)=="049")
			value = value.substr(1);
		else if (value.substr(0,2)=="49")
			value = value;
		else if (value.substr(0,2)=="01")
			value = "49" + value.substr(1);
		if (value.length != 11 || value.length != 12)
			value = "";	
	}
	else
	{
		//be - Mobile Phones - Base +32 485 486  	Mobistar +32 495 496 49 	Proximus 	+32  472 473 47 - begin with 04xx and subscriber number is six digits long
		if (value.length == 10 && value.substr(0,2)=="04")
			value = "32" + value.substr(1);
		else if (value.length == 13 && value.substr(0,2)=="00")
			value = "32" + value.substr(4);
		else if (value.length == 9 && value.substr(0,1)=="4")
			value = "32" + value;
		if (value.length != 11 || value.substr(0,2)!="32")
			value = "";	
	}
	return value;
}
function split( val ) {
	return val.split( / - \s*/ );
}
function extractLast( term ) {
	return split( term ).pop();
}
function extractFirst( term ) {
	return split( term ).shift();
}
// pre-submit callback 
function validate(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    //var queryString = $.param(formData);	
	//
	var result = true;
	$('form li').removeClass("error");
	//$('input[type!=checkbox]').each(function(){
	$('input.required').each(function(){
		var value = $(this).fieldValue(); 
		if (!value[0]){
			$(this).parents("li:first").addClass("error");
			result = false;
		}
	});
	var form = jqForm[0]; 
    return result; 
} 
 
// post-submit callback 
//function processResponse(responseText, statusText, xhr, $form)  { 
function processResponse(data) { 
    // 'data' is the json object returned from the server 
    alert(data.message); 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +       '\n\nThe output div should have already been updated with the responseText.'); 
} 

//ui-automcomplete
function log( message ) {
	$( "<div/>" ).text( message ).prependTo( "#log" );
	$( "#log" ).attr( "scrollTop", 0 );
}

/* validation functions */

function IsNumeric(input){
	var RE = /^-{0,1}\d*\.{0,1}\d+$/;
	return (RE.test(input));
}
// loose email validation check
function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1)
	   return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	   return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
		return false;
	 if (str.indexOf(at,(lat+1))!=-1)
		return false;
	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
		return false;
	 if (str.indexOf(dot,(lat+2))==-1)
		return false;
	 if (str.indexOf(" ")!=-1)
		return false; 
	 return true;					
}

function hasValue(element)
{
	if ($(element).attr('type')=="text")
		return ($.trim($(element).val()).length > 0);
	else if ($(element).attr('type')=="checkbox")
		return ($(element).checked);
	else if ($(element).attr('type')=="radio")
	{	
		var res = false;
		var selector = 'input[name="'+ $(element).attr('name') +'"]';
		var radios = $('input[name="'+ $(element).attr('name') +'"]');
		var i =0;
		for(i=0;i<radios.length;i++) {
			if($(radios)[i].checked == true) res = true;
		}
		return res;
	}
	else
	{
		return ($.trim($(element).val()).length > 0);
	}		
}
