/*

Version: 1.3 (29-04-11)


TODO
	Speed: Start Load AJAX, FadeOut, OnLoaded FadeIn
	SEO: Support add # dynamic

29-04-11:
	Popup width & height
	
28-04-11:
	noajax class
	quicksand
	...

22-03-11:
	ui-state-default
	attribute message
	class normallink
	data-id => output-sel
	Same Function On receiving AJAX data !! MERGE !!
	

*/
var relink = true;
var default_content="";
//var base = "http://localhost/slowtrick/";	Should be set by the style
var lasturl="";

	
$(document).ready(function(){

	$( "form" ).live("submit",function( event ){
		
		if(!$(this).hasClass('ajax')) return;
		//Do nothing
		if($(this).hasClass('noajax')) return;	
		
		event.preventDefault();
		
		var form = $( this );
		
		if($(this).hasClass('href')) {
			var action = $(this).attr('action');
		} else {
			var action = form.attr('action');
		}
		
		$.ajax({
		  url: action,
		  context: this,
		  type: 'post',
		  data: $(this).serialize(),
		  dataType: "json",
		  success: AJAX_Succes
		});

		// Prevent the form submission (default action).
	});
	
		
	$('a, a.button').live('click', function(e) {
		
		url=$(this).attr('href');
		uri=$(this).attr('href').replace(base,'');	//Remove base
		var hash = window.location.hash;
		console.log(uri);
		//Do not react on #
		if(uri == '#') { window.location.hash = lasturl;return; }
		
		//Do nothing
		if($(this).hasClass('normallink')) return;
		if($(this).hasClass('noajax')) return;
		
		if(! ($(this).hasClass('ajax') || $(this).hasClass('stay'))) return;

		//No way back we do AJAX..
		e.preventDefault();

		
		if($(this).hasClass('ajaxform')) { 
			$.ajax({
			  url: url,
			  context: this,
			  type: 'post',
			  dataType: "json",
			  success: AJAX_Succes
			});
			return;
		}
		
		if($(this).hasClass('popup')) { 
			popitup( $(this).attr('href'), $(this).attr('popup-width'), $(this).attr('popup-height')); 
			//e.preventDefault(); 
			return; 
			
		}
		
		if($(this).attr('dialog-open') ){
			$( $(this).attr('dialog-open') ).dialog( "open" );
		}
		

	
		if($(this).hasClass('dialog')) { 
			var title = $(this).attr('dialog-title');
			var width = 900;
			var height = 500;
			
			if($(this).attr('dialog-width')) width = $(this).attr('dialog-width');
			if($(this).attr('dialog-height')) height = $(this).attr('dialog-height');
			var settings = {'title':title,width:Number(width),'height':Number(height),modal:'false'};

			showdialog(url,settings);
		
			//prevent the browser to follow the link
			//return false;
			return;
		}
		
		
		if($(this).hasClass('prevent')) return;
		
		
		changeHash(uri); //Optimise: quicker no waiting on interval
		
		return false;
	});
	
	//Back Button Support
	//setInterval("checkURL()",250);
	/*$(window).bind('hashchange', function () { //detect hash change	
		var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
		//console.log(hash);
		checkURL(hash);
	});
	checkURL();*/

	dialogcontainer = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');

});


var dialogcontainer;

function dialogHT(url, settings) {
	$.ajax({
		type: "POST",
		url: url,
		dataType: "json",
		success: function(data){
			$('#dialog').html(data.form);	
			initScripts();
			$('#dialog').dialog(data);			
		}
	});
}
function showdialog(url, settings) {

	$('#dialog').load(
		url,
		{},
		function(responseText, textStatus, XMLHttpRequest) {
			//console.log( settings );
			initScripts();
			$('#dialog').dialog(settings);
		}
	);
}

function changeHash(val) {
	checkURL(val);	
	lasturl = val;
	window.location.hash = val;
}


function checkURL(hash,refresh)
{
	if(!hash) hash=window.location.hash;
	
	//console.log(hash);
	//console.log(lasturl);
	
	if(hash != lasturl || refresh)
	{
		lasturl=hash;
		changeContent(hash);
	}
}



//Show Hide Ani
function changeContent(url)
{
	url=url.replace('#','');	//Remove #

	$('#loading').css('visibility','visible');
	//$("#content").fadeOut("fast", test );
	//$("#content").hide();

	
		$.ajax({
			type: "POST",
			url: base+url,
			dataType: "html",
			success: function(msg){
				
				if(parseInt(msg)!=0)
				{
					//$('#content').html(msg).fadeTo("slow", 1);
					$('#content').html(msg);
					$('#loading').css('visibility','hidden');
					initScripts();
				}
			}
		}); 
}

function initScripts() {
	$( "input:submit, .button, button, .buttons a" ).button();
		
	$('form').submit(function() {
		$('input.error').val("");	//Remove error messages
		$('.formdesc').val("");	//Remove Desc messages
	});
	
}




function AJAX_Succes(data) {

	//console.log(data);
	eval(data);
	//console.log($(this));
	if(data.success) {
		//console.log('hee');
		message(data.message);
		$('#dialog').dialog( "close" );
		return;
	}
	
	
	//Hide the form?
	sel = $(this).attr('hide-sel');
	if(sel) {
		$(sel).fadeOut();
	}
	
	//Redirect
	sel = $(this).attr('redirect');
	if(sel) {
		checkURL(sel,true);
	}
	
	//Refresh page
	if($(this).attr('refresh') == 'true') { 
		checkURL(this.hash,true);
	}
	//Refresh page - for all site blocks or for some JS?
	if($(this).attr('refresh-full') == 'true') { 
		location.reload(true);
	}

	
	//Need to refresh some based on the form?
	sel = $(this).attr('refresh-sel');
	if(sel) {
		url = $(sel).attr('data-url');
		$(sel).fadeTo('fast', 0.1, function() {
			$.ajax({  url: url,context: sel, success: function(data){ $(sel).html(data).fadeTo('fast',1);  }	});
		});
	}
	

	if($(this).attr('message') == 'true') {
		message(data);
	}
	
	//HTML Message => the data-id or display to the message handler?
	place = $(this).attr('output-sel');
	if( place ) {	//Container to place AJAX data
		$(place).fadeOut("fast").html(data).fadeIn("fast");
	}

	
}










function message(txt) {	
var options = {id: 'message_from_top',
			   position: 'top',
			   size: 50,
			   backgroundColor: 'rgba(70, 70, 70, 0.8)',
			   delay: 2500,
			   speed: 500,
			   fontSize: '30px'
			  };
	$.showMessage(txt, options);
}
	
$(document).ready(function(){
	

	$( "input:submit, .button, button, .buttons a" ).button();
		
	
	$('form').submit(function() {
		$('input.error').val("");	//Remove error messages
		$('.formdesc').val("");	//Remove Desc messages
	});
	
	$('.error').live('focus', function() {
	  $(this).val("");
	  $(this).removeClass( 'error' )
	});
	
	$('.formdesc').live('focus', function() {
	  $(this).val("");
	  $(this).removeClass( 'formdesc' )
	});
	
		
	
	$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
	$('.quicksand').live('click', function(e) {
		var val = $(this).attr('href');  
		changeHashQuiet(val);
		
		val=val.replace('#','');	//Remove #
		url = base+val+'?listonly=true';
		$.get( url, function(data) {
			$('.ajaxcontent').quicksand( $(data).find('li') );
		});
		e.preventDefault();	
	});
	
	
	//Some auto hiding stuff
	$('.hide_action').live('mouseover mouseout', function(event) {
	  if (event.type == 'mouseover') {
		$(this).children(".actions").show();
	  } else {
		$(this).children(".actions").hide();
	  }
	});

	//checkURL();
	
	//LightBox
	/*$('.gallery a').lightBox({
		imageLoading: base+'plugins/lightbox/images/loading.gif',
		imageBtnClose: base+'plugins/lightbox/images/close.gif',
		imageBtnPrev: base+'plugins/lightbox/images/prev.gif',
		imageBtnNext: base+'plugins/lightbox/images/next.gif',
	});*/


	
	//filling in the default content
	default_content = $('#content').html();	
});


function popitup(url,width,height) {
	if(width == null) width = 500;if(height == null) height = 400;
	//newwindow=window.open(url,'name','height=500,width=450');
	newwindow=window.open(url,'name','resizable=yes,height='+height+',width='+width);
	if (window.focus) {newwindow.focus()}
	return false;
}	


