/*
Author	: Ronnie Chong
Date	: 8th December 2011
Version	: 1.0.0

*/

//preload
var numImg=0;
var arrBgImagesAssets = new Array();
var xmlphoto = './_assets/_script/imgphoto.xml';
var pathLogin = './_assets/_page/login.php';
var pathLogout = './_assets/_lib/logout.php';
var pathShowcase = './_assets/_page/showcase.php';
var pathShowcaseLink = './_assets/_lib/showcaselink.php';
var pathPage = './_assets/_page/';
var pathAuth = './_assets/_lib/auth.php';
var htmlPreloader = '<div id="pageload"></div>';
var htmlPreloader2 = '<span class="imgpre"><img src="./_assets/_img/preloader.gif" width="160" height="24" border="0"/></span>';
var htmlphotoloc = "<strong>Location: </strong>";
var htmlphotodate = "<strong>Date taken: </strong>";
var htmlphotosettings = "<strong>Settings: </strong>";
var strDefaultShowcase = "portcurrent";
var strDefaultPrefix = "showcase_";
var strDefaultSelection = "<span>&#58;&#58; </span>";
var strCurrentShowcase = '';
var arrError = new Array();
var currPg = '';
arrError[0] = 'Page cannot be found';

var indicator_delay = 20000;

var allow_cookies = true;
var allow_indicator = true;

$(document).ready(function(){
	 preSetup();
	$("#jquery li").each(function() {
		$("a strong", this).css("opacity", "0");
	});
	
	$("#jquery li").hover(function() { // Mouse over
		$(this)
			.stop().fadeTo(500, 1)
			.siblings().stop().fadeTo(500, 0.2);
			
		$("a strong", this)
			.stop()
			.animate({
				opacity: 1,
				top: "-10px"
			}, 300);
		
	}, function() { // Mouse out
		$(this)
			.stop().fadeTo(500, 1)
			.siblings().stop().fadeTo(500, 1);
			
		$("a strong", this)
			.stop()
			.animate({
				opacity: 0,
				top: "-1px"
			}, 300);
	});
	
	
	$( "#imginfoholder" ).hide();
	var imgcontainer = $( "#imginfoholder" );
	$( "a.imgnav_info" ).click(function( event ){
		event.preventDefault();
		imgcontainer.animate({ "height": "toggle", 
							   "opacity": "toggle"
								}, "slow");
		
	});
	
	$(".imgnav_prev").click(function(event){
 	     event.preventDefault();
		 numImg--;
		 setImgBg();
	 });
	
	$(".imgnav_next").click(function(event){
		 event.preventDefault();							 
		 numImg++;
		 setImgBg();
	 });
	 
	 $( "#panelNav .panel" ).click(function(event){
		event.preventDefault();
		container.slideUp( 500, function(){
			$("#contentHolder").html('');
		});
	 });
	 
	 var container = $( "#panelcontainer" );
	 $('#navmenu a').click(function(event){
		 event.preventDefault();
		 if (currPg=='') currPg = id;
		 var id= $(this).attr('id');
		 if (id=='home'){
			 window.location.replace("./"); 
		 }else{
			 var path = pathPage + id + '.html';
			 if (container.is( ":visible" )){
				 if (currPg!=id){
					 container.slideUp( 500 ,function(){
						 $("#contentHolder").html('');
						 }).slideDown(500, function(){
							loadContentPage('#contentHolder',path,id); 
							});
					  currPg = id;
				 }else{
					  container.slideUp(500,function(){
						 $("#contentHolder").html('');
						});
					  currPg='';
				 }
			 }else{
				   $("#contentHolder").html('');
				   container.slideDown( 500 ,function(){
					   loadContentPage('#contentHolder',path,id);
				   });
				   currPg = id;
			 }//if (container.is( ":visible" ))
		 }//if (id=='home')
	 });
	 
});

function showError(msg, xhr){
	var str = '<p align="center"> Error - '+ xhr.status + " " + xhr.statusText+' : '+msg+'</p>';
	return str;
}

function loadContentPage(div, str,id){
	$(div).html(htmlPreloader);
	$(div).load(str, function(response, status, xhr) {
	  if (status == "error") {
		$("#contentHolder").html(showError(arrError[0],xhr));
	  }else{
		  if (id=='about'){
			  Shadowbox.clearCache();
			  Shadowbox.init({
					skipSetup: false
			  });
			  Shadowbox.setup();
		  }else if (id=='portfolio'){
			  setInfoPanel(false);
			  initLogin();
		  }
		  $(this).hide().fadeIn(1000);
	  }
  });
}

function preSetup(){
	$('BODY').append('<div id="preloader"></div>');

	if (allow_cookies){
		if ($.cookie('userimgnum')==null){
			$.cookie('userimgnum',numImg , {expires: 7, path: '/'});
		}else{
			numImg = $.cookie('userimgnum');
		}
		
		if (allow_indicator){
			if ($.cookie('indicator')==null){
				$.cookie('indicator',false , {expires: 7, path: '/'});
				$('#indicatorphotos').delay(indicator_delay).fadeOut();
				$('#indicatorsocial').delay(indicator_delay).fadeOut(500,function(){
					$.cookie('indicator',true , {expires: 7, path: '/'});			   
				});
			}else{
				if ($.cookie('indicator')){
					$('#indicatorphotos').fadeOut(500);
					$('#indicatorsocial').fadeOut(500);
				}
			}
		}
	}
	$('#preloader').css({"opacity":0.75});
	$.ajax({
		url: xmlphoto, 
		dataType: "xml", 
		success: setupImgAssets, 
		error: function(){
				$.backstretch('./_assets/_img/mainbg01.jpg', {speed: 1000});
				$('.nav-buttons').hide();
				$('BODY #preloader').remove();
			}
  });
	
}

function setupImgAssets(xml){
	 $(xml).find("photo").each(function(){
		var strid= $(this).find('id').text();
		var strpath = $(this).find('path').text();
		var strlocation = $(this).find('location').text();
		var strdate = $(this).find('date').text();
		var strsettings = $(this).find('settings').text();
		
		arrBgImagesAssets.push({
            id: strid, 
			path: strpath, 
            location:  strlocation,
			date:  strdate,
			settings:  strsettings
        });
		 
	  });
	 //preload
	$(arrBgImagesAssets).each(function() {
		var image = $('<img />').attr('src', this.path);
	});
	
	setImgBg();
}


function loadcomplete(){
	if ($('BODY #preloader')) $('BODY #preloader').remove();
}
function setImgBg(){
	if (allow_cookies) $.cookie('userimgnum',numImg);
	if (numImg<0){
		numImg = arrBgImagesAssets.length-1;
    }else if (numImg>(arrBgImagesAssets.length-1)){
		numImg = 0;
	}
	$.backstretch(arrBgImagesAssets[numImg].path, {speed: 1000}, loadcomplete);
	var strhtml = htmlphotoloc + arrBgImagesAssets[numImg].location+"<br/>";
	strhtml += htmlphotodate + arrBgImagesAssets[numImg].date+"<br/>";
	strhtml +=htmlphotosettings + arrBgImagesAssets[numImg].settings;
	
	$('#imginfoholder .imginfo').html(strhtml).hide().fadeIn(700);
	
}

function setInfoPanel(bFlag){
	if (bFlag){
		$('#portfolioInfoBox').load(pathShowcaseLink, function(response, status, xhr) {
				$(this).slideDown(100);	
				initLogout();
				initShowCaseLink();
		});
	}else{
		$('#portfolioInfoBox').fadeOut(300);
	}
}

function initShowCaseLink(){
	$('#showcaseHolder').html(htmlPreloader);
	strCurrentShowcase = (strCurrentShowcase.length<=0)?strDefaultShowcase:strCurrentShowcase;
	var strPort =  pathPage + strDefaultPrefix +strCurrentShowcase +'.php';
	$('#portfolioInfoPanel a#'+strCurrentShowcase).addClass('showcasecurrent');
	$('#portfolioInfoPanel a#'+strCurrentShowcase).prepend(strDefaultSelection);
	$('#showcaseHolder').load(strPort, function(response, status, xhr){
		
		if (status=='error'){
			$(this).html(showError(arrError[0],xhr));
		}else{
			$(this).hide().fadeIn(700);
			initShowCaseSlider('#coda-slider-'+strCurrentShowcase);
			Shadowbox.clearCache();
			Shadowbox.init({
					skipSetup: false,
					players:    ["swf","flv","img","html","iframe"],
					flashParams:{bgcolor:"#ffffff"},
					overlayOpacity:0.90,
					flashVersion: "8.0.0"
					
			  });
			Shadowbox.setup();
			initZoomThumbnail();
		}
	})
	$('#portfolioInfoPanel a').click(function(event){
		var id = $(this).attr('id');
		if (id=='portresume'){
			
		}else{
			event.preventDefault(); 
			strCurrentShowcase = $(this).attr('id');
			$('#portfolioInfoPanel a').each(function(){$(this).removeClass('showcasecurrent');$('span',this).remove();});
			$(this).addClass('showcasecurrent');
			$(this).prepend(strDefaultSelection);
			var strPort = pathPage + strDefaultPrefix + strCurrentShowcase +'.php';
			$('#showcaseHolder').html(htmlPreloader);
			$('#showcaseHolder').load(strPort, function(response, status, xhr){
				if (status=='error'){
					$(this).html(showError(arrError[0],xhr));
				}else{
					$(this).hide().fadeIn(700);
					initShowCaseSlider('#coda-slider-'+strCurrentShowcase);
					Shadowbox.clearCache();
					Shadowbox.init({
						skipSetup: false,
						 players:    ["swf","flv","img","html","iframe"],
						flashParams:{bgcolor:"#ffffff"},
						overlayOpacity:0.90,
						flashVersion: "8.0.0"
					});
					Shadowbox.setup();
					initZoomThumbnail();
				}					 
			});
		}
	  });
	
}

function initZoomThumbnail(){
	//move the image in pixel
	var move = -15;
	
	//zoom percentage, 1.2 =120%
	var zoom = 1.2;

	//On mouse over those thumbnail
	$('.zitem').hover(function() {
		
		//Set the width and height according to the zoom percentage
		width = $('.zitem').width() * zoom;
		height = $('.zitem').height() * zoom;
		
		//Move and zoom the image
		$(this).find('img').stop(false,true).animate({'width':width, 'height':height, 'top':move, 'left':move}, {duration:200});
		
		//Display the caption
		$(this).find('div.caption').stop(false,true).fadeIn(200);
	},
	function() {
		//Reset the image
		$(this).find('img').stop(false,true).animate({'width':$('.zitem').width(), 'height':$('.zitem').height(), 'top':'0', 'left':'0'}, {duration:100});	

		//Hide the caption
		$(this).find('div.caption').stop(false,true).fadeOut(200);
	});
	
	$('.zitemsmall').hover(function() {
		
		//Set the width and height according to the zoom percentage
		width = $('.zitemsmall').width() * zoom;
		height = $('.zitemsmall').height() * zoom;
		
		//Move and zoom the image
		$(this).find('img').stop(false,true).animate({'width':width, 'height':height, 'top':move, 'left':move}, {duration:200});
		
		//Display the caption
		$(this).find('div.caption').stop(false,true).fadeIn(200);
	},
	function() {
		//Reset the image
		$(this).find('img').stop(false,true).animate({'width':$('.zitemsmall').width(), 'height':$('.zitemsmall').height(), 'top':'0', 'left':'0'}, {duration:100});	

		//Hide the caption
		$(this).find('div.caption').stop(false,true).fadeOut(200);
	});
	
	$('.zitemmedium').hover(function() {
		
		//Set the width and height according to the zoom percentage
		width = $('.zitemmedium').width() * zoom;
		height = $('.zitemmedium').height() * zoom;
		
		//Move and zoom the image
		$(this).find('img').stop(false,true).animate({'width':width, 'height':height, 'top':move, 'left':move}, {duration:200});
		
		//Display the caption
		$(this).find('div.caption').stop(false,true).fadeIn(200);
	},
	function() {
		//Reset the image
		$(this).find('img').stop(false,true).animate({'width':$('.zitemmedium').width(), 'height':$('.zitemmedium').height(), 'top':'0', 'left':'0'}, {duration:100});	

		//Hide the caption
		$(this).find('div.caption').stop(false,true).fadeOut(200);
	});

}

function initShowCaseSlider(div){
	$(div).codaSlider({
		crossLinking: false,
		dynamicArrows: false,
		dynamicTabs: true,
		panelTitleSelector: "h3.title",
		firstPanelToLoad: 1
	});	
}

function initLogin(){
	
	$('.divportfolio').html(htmlPreloader);
	$('.divportfolio').load(pathLogin, function(response, status, xhr) {
		initLoginForm();
	});
}


function initLoginForm(){
	$('#frmlogin #btnsubmit').click(function(event){
											 
		var form_data = {user: $('#frmlogin #username').val(),
						 pass: $('#frmlogin #userpass').val(),
						 site: 'main',
						 is_ajax:1};
		$(this).attr("disabled", true);
		$('#frmFd').html(htmlPreloader2);
		$.ajax({
			type: "POST",
			url: pathAuth,
			data: form_data,
			success: function(response){
				$('#frmFd').removeClass('frmgreen').removeClass('frmred');
				if(response == '1'){
					$('#frmFd').html("Logging in success").addClass('frmgreen').hide().fadeIn(900).fadeOut(500,function(){
							$('.divportfolio').html(htmlPreloader);
							$('.divportfolio').load(pathShowcase, function(response, status, xhr) {
							   setInfoPanel(true);
							});
					});
				}else{
					$('#frmFd').html("Invalid username and/or password.").addClass('frmred').hide().fadeIn(700).delay(800).fadeOut(700);
					$('#frmlogin').clearForm();
					$('#frmlogin #btnsubmit').attr("disabled", false);
				}
				
			}
		});
		return false;
	});
}

function redirectPage(str){
	$('.divportfolio').html(htmlPreloader);
	$('.divportfolio').load(str, function(response, status, xhr) {
		  if (str==pathShowcase) {
			  setInfoPanel(true);
		  }
		  if (str==pathLogin) initLogin();
	});
}

function initLogout(){
	$('#showcaseLogout').click(function(event){		
		event.preventDefault();
		var form_data = {is_ajax:1};
		$.ajax({
			type: "POST",
			url: pathLogout,
			data: form_data,
			success: function(response){
				if (response==1) {
					setInfoPanel(false);
					redirectPage(pathLogin);
				}
			}
		});
	});
}

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};
