$(document).ready(function() {
	
	//detect the browser with
	if ($(window).width() < 1260) {
		$('#wrapper').css('width','911px');
		$('#content').css('width','921px');
		init(3);
	} else{
		init(4);
	}
	
	//fb
	$('a.facebook').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		shareIt(20, "-","-");
		return false;
	});
	
	//twit
	$('a.twitter').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		shareIt(10, "-","-");
		return false;
	});
	
});
	
function init(colls) {
		
	buildPage(colls);
	
	//login
	$('a.tease').click(function() {
		overlayPanel("tease.php");
	});
	//close nyroModal
	$('a.nyroModalClose').click(function() {
		$.nyroModalRemove();
	});
	
	//login
	$('a.login').click(function() {
		overlayPanel("login.php");
	});
	//register
	$('a.register').click(function() {
		slidePanel("register.php");
	});
	//personalize
	$('a.personalize').click(function() {
		//Cancel the link behavior
		//e.preventDefault();
		slidePanel("personalize.php");
	});
	
	//send an email
	/*$('a.mail').click(function() {
		overlayPanel("mail.php");
	});
	*/
}

function newsLetter(){
	overlayPanel("newsletter.php");
}

function sendMail($userAlias) {
	
	overlayPanel("mail.php?uA="+$userAlias);
}

function slidePanel($pageUrl){
	//excits?
	if ($('#rlayer').length != 0) return;
	
	$.get("_include/"+$pageUrl, {},
		function(content){
			//alert( content );
				
			var subscribeItem =  $("#wrapper").append( $(content) );
				
				//set the dimensions
				$('#rlayer').width(10);
				var panelH = $("#wrapper").height()-375;
				//$('#rlayer').heightpanelH);
				var actualH = $('#rlayer .inner').height();
				panelH = Math.max(panelH, actualH);
				
				$('#rlayer').animate({
				    width: '620px',
					height: panelH+'px'
				  }, 500);

				tabInit();
				
				$('.close-panel').click(function() {
					closePanel();
				});
				
				initForm();
	    	}
		); 
}

function overlayPanel($pageUrl){
	
	$.nyroModalManual({
		//debug: true,
		//	modal: true,//no clicking bg or esc
		//	closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>', // Adding automaticly as the first child of #nyroModalWrapper 
		bgColor: (bSpecial)? "#000":"#FFF",
		url: "_include/"+$pageUrl,
		height: null, // default Height If null, will be calculate automatically
		width: 660,
		minWidth: 660
	});
}

function closeOverlayPanel(){
	$.nyroModalRemove();
}

function closePanel(){
	$('#rlayer').animate({  width: 'hide' }, 400, function() {
		 // Animation complete.
		 $('#rlayer').remove();
	});
};
	
function initForm(){
	
	$.validator.messages.required = jQuery.format("");

	//special validation for passwords etc
	$("#theForm").validate({
		rules: {
			password: {
				minlength: 8
			},
			_password: {
				minlength: 8,
				equalTo: "#password"
			}
		},
		messages: {
			password: {
				//required: "Please provide a password",
				minlength: "Your password must be at least 8 characters long"
			},
			_password: {
				//required: "Please provide a password",
				equalTo: "Please enter the same password as above"
			}
		},
		showErrors: function(errorMap, errorList) {			
			//check tabs!
			//var element = $($.each(errorList)[0].element);
			if(errorList[0] != undefined){
				var element = $(errorList[0].element);
				var tab =  element.parents().filter('.tab_content');
				if(tab) tabClick(tab);
			}
			
			this.defaultShowErrors();
		}
	});
	
	//for the date
	$(".DatePicker").each(function(){
		$(this).datepicker({
			dateFormat: 'dd-mm-yy',
			changeMonth: true,
			changeYear: true,
			yearRange: '1950:2000'
		});
	});
	
	//personalize checkboxes
	$(".scrollfield .select-all").click(function(){
		$(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
    });
}

function submitForm(){
	
	var url = "_include/form-send.php";
		
	var options = {
		url:			url,
		target: 		'#formMsg',
        beforeSubmit:   validateForm,  // pre-submit callback 
        success:        saveResponse,  // post-submit callback 
		error:          saveError,
		dataType:  	    'json' 
    };	
	$('#theForm').ajaxSubmit(options);
	
	return false;
}
// pre-submit callback 
function validateForm(formData, jqForm, options) { 
	
	var success = true;	
	if (! $('#theForm').valid() ) success = false;
	
	if(success){
		//$('span.form-tab').html('<div style="text-align:center"><img src="imgs/loader.gif" alt="loading" width="16" height="16" border="0"></div>');
	}

	return success;
}


// post-submit callback 
function saveResponse(data, statusText, xhr, $form)  {
	
	$('html, body').animate({scrollTop:0}, 'slow');
	
	if(data == null || data.success == 0){
		
		if(data == null || data.msg == undefined){
			//wrong json
			//var jsLink = (dSingle)? "showForm()":"closeForm()";
			//$("#formMsg").html("Wrong json format:<br /><br /><pre>"+data+"</pre><br><br><a href='javascript:"+jsLink+"'>Click here</a> to close.");
		} else {
			//$("#formMsg").html(data.msg + "<br /><br /><a href='javascript:showForm()'>Click here</a> to try again.");
			//shwo the error
			alert(data.msg);
		}
		
		//show form
		$('div.success-tab').css("display", "none");
		$('div.form-tab').css("display", "block");
		$('p.form-tab2').css("display", "block");
		
	//success!
	} else if(data.success){
	
		if(data.redirect) {
			$(location).attr('href',data.redirect);
			return;
		}
	
		//show message
		$('div.success-tab').css("display", "block");
		$('div.form-tab').css("display", "none");
		$('p.form-tab2').css("display", "none");
	}
}

function saveError(data, statusText) { 
	
	//alert("Something went wrong.\nProbably the wrong json format.\n\nClick \"ok\" to close");
	
	//alert(data["responseText"]);
	//show form
	$('div.success-tab').css("display", "none");
	$('div.form-tab').css("display", "block");
	$('p.form-tab2').css("display", "block");
}


function shareIt(id, titleStr, linkStr){
	
	var t = (titleStr.length>4)? titleStr:document.title;
	var u = (linkStr.length>10)? linkStr:location.href;
		
	//u += "?st=6"
	//var u = "www.atlasreizen.be/mensen/wiet-proesmans/";
	
	var url = "";
	var w = 700;
	
	switch(id) {
		case 10: //twitter
			url = "http://twitter.com/home?status=" + encodeURIComponent(t);// +" " + u.replace("#", "%23");
			w = 800;
			break;
		case 20: //facebook
			//url = "http://www.facebook.com/sharer.php?u="+ encodeURIComponent(u);// +"&t="+encodeURIComponent(t);
			url = "http://www.facebook.com/sharer.php?u="+ encodeURIComponent(u);// +"&t="+encodeURIComponent(t);
			//url = "http://www.facebook.com/sharer.php?u="+u;
			//url = "http://www.facebook.com/share.php?u=" + encodeURIComponent(u);
			break;
	}
	
	window.open(url,'sharer','toolbar=0,status=0,width='+w+',height=436');
}

function simple_tooltip(target_items, name){
 
	$(target_items).each(function(i){
		
		$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
		var my_tooltip = $("#"+name+i);

		if($(this).attr("title") != ""){ // checks if there is a title

			$(this).removeAttr("title").mouseover(function(){
					my_tooltip.css({opacity:1, display:"none"}).fadeIn(300);
			}).mousemove(function(kmouse){
					my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
			}).mouseout(function(){
					my_tooltip.fadeOut(300);
			});

		}
	});
}


