/*

Version: 1.5 (29-04-11)


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

4-7-11:
	baseurl

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="";
var quietHashChange = false;


$(document).ready(function(){
	
	$('.quicksandnav').live('click', function(e) {
		var val = $(this).attr('href');  
		changeHashQuiet(val);
		
		$('.quicksandnav').removeClass("current");
		$(this).addClass("current");
		
		
		val=val.replace('#','');	//Remove #
		url = baseurl+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
	// Select all links that contains lightbox in the attribute rel
	// Select all links in object with gallery ID
	// Select all links with lightbox class
	$('.gallery a, a.lightbox, .gallery a, a[rel=lightbox]').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',
	});

			
			
	$('a').live('click', function(e) {
		
		//Do nothing
		if($(this).hasClass('normallink')) return;
		if($(this).hasClass('noajax')) return;
		if($(this).hasClass('ui-state-default')) return;
		if($(this).attr('href') == 'javascript:void(0);') return;

		//Cancel out none ajax calls?
		if(!$(this).hasClass('ajax') && !$(this).hasClass('stay')) return;
		
		
		//No way back we do AJAX..
		e.preventDefault();
		
		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')) { 
		//AJAX
			var url = $(this).attr('href');
			var dialog = $('<div style="display:hidden"></div>').appendTo('body');
			// load remote content
			
			/*var data;
			if($(this).attr('serialize') ) {
				data = $("#"+$(this).attr('serialize')).serialize();
				console.log(data);
			}*/
			var title = $(this).attr('dialog-title');
			var width = 900;//$(this).attr('dialog-width');		BUG NOT WORKING????
			var height = $(this).attr('dialog-height');
			//console.log(breedd);
			dialog.load(
				url,
				{},
				function(responseText, textStatus, XMLHttpRequest) {
					dialog.dialog({title:title,width:width,height:height,modal:'false'});
				}
			);

			//prevent the browser to follow the link
			return false;
		} 
		
		
		if($(this).hasClass('prevent')) return;
		
		//Image?
		/*if($(this).hasClass('lightbox')) {
			$(this).lightBox(); // Select all links in the page
			return;
		}*/
		
		url=$(this).attr('href');
		uri=$(this).attr('href').replace(base,'');	//Remove base
		
		if($(this).hasClass('stay')) {	//A way to do simple AJAX calls => form links
			
			if($(this).hasClass('delete'))	$(this).parent().parent().hide('slow');
			if($(this).hasClass('add'))	{ checkURL(0,true); }
				
			$.ajax({
			  type: "POST",
			  dataType: "html",
			  url: url,
			  context: this,
			  success: AJAX_Succes
			});
			
		} else {
			//checkURL(uri);
			//window.location.hash = uri;
			changeHashQuiet(uri); //Optimise: quicker no waiting on interval
		}
		
		return false;
	});
	
	$( "form" ).live("submit",function( event ){
		
			if(!$(this).hasClass('ajax')) return;
			//Do nothing
			if($(this).hasClass('noajax')) return;
		
			event.preventDefault();
			
			var form = $( this );
			
			var action = form.attr('action');
			//console.log(action);
			
			$.ajax({
			  url: action,
			  context: this,
			  type: 'post',
			  data: $(this).serialize(),
			  success: AJAX_Succes
			});

			// Prevent the form submission (default action).
		}
	);
	
	//Back Button Support
	setInterval("checkURL()",250);
	/*$(window).bind('hashchange', function () { //detect hash change	
		if(quietHashChange) return;
		var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
		console.log(hash);
		checkURL(hash);
	});*/
	
	//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;
}	

//---------
// Set the Section
//---------
function changeSection(section) {
	$('#bgimg').attr("src", base+'assets/style/backgrounds/'+section+'.jpg');
	setCookie("section",section,365);
	checkURL(this.hash,true);
}


//---------
/* What can this do?
	<li class='hide_action'><a class='stay' data-id='session' href='<?=url("sessions/session/$item->sessionsID/")?>'>
	<span class='date'><?=prettydate($item->startdate)?></span> 
	<?=$item->name?> (<?=$duration?> hours)</a>
	<span class='actions' style='display:none;' >
		<a class='delete stay' href='<?=url("sessions/del/$item->sessionsID")?>'><?=icon('delete')?></a>
	</span>
	</li>
	*/
//---------
function AJAX_Succes(data) {
	
	//console.log(data);
	//console.log($(this));
	
	//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);  }	});
		});
	}
	
	/*
	place = $(this).attr('data-id');
	if( place ) {	//Container to place AJAX data
		$('#'+place).fadeOut("fast").html(data).fadeIn("fast");
	} else {
		message(data);
	}*/
	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 changeHashQuiet(val) {
	lasturl = val;
	window.location.hash = val;
}


function checkURL(hash,refresh)
{
	if(!hash) hash=window.location.hash;
	
	if(hash != lasturl || refresh)
	{
		lasturl=hash;
		
		// FIX - if we've used the history buttons to return to the homepage,
		// fill the pageContent with the default_content
		
		//if(hash=="")
		//$('#content').html(default_content);
		
		//else
		changeContent(hash);
		
	}
}



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

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

}



//--------------------------------------
// Cookie Stuff
//--------------------------------------
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");

  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
