var Site = {
	showId : null,
	lang : "pl",
	initiated : false,
	init: function () {		
		Site.addressMenu();
		Flash.init();
		Images.init();
		Site.doAddThis();
		Chimp.init();
		Ftp.init();
		if(Site.initiated == false) Site.initOnce();
	},
	initOnce : function(){
		Site.initiated = true;
		Pdf.init();
		$(document.documentElement).keyup(KeyNav.keyup);
	},
	addressMenu : function () {
			$("a:not([href=\"#\"]):not([href*=\"http:\"]):not([href*=\"mailto:\"]):not([href*=\"getfile.php\"]), a[href*=\"ilike-photo.com\"]").address(function () {
				return $(this).attr('href').replace(location.pathname, '').replace("#", '');
			});
	},
	onChange: function (e) {
			if (window.location.pathname.length > 1) {
				window.location = "http://" + window.location.host + "#" + window.location.pathname;
			}
			var page;
			switch(e.pathNames[0]){
				case undefined:
					page = "start";
					Site.loadSite(page,e.pathNames[1],e.pathNames[3],e.pathNames[5]);
					break;
				case "pdf":
					Site.removeContent();
					setTimeout(function(){document.title = "PDF Download - I LIKE PHOTO Group"; $("header").after(Pdf.drawPdf()); Pdf.initSorting(); $("section").hide().fadeIn(500);},300);
					break;
				default:
					page = e.pathNames[0];
					Site.loadSite(page,e.pathNames[1],e.pathNames[3],e.pathNames[5]);
			}
			$("#menu").children().removeClass("selected");
			$("#menu").find("a[href='/" + page + "']").parent().addClass("selected");
	},
	removeContent: function () {
		if ($("section").length) {
			$("section").fadeOut(300, function () {
				$(this).remove()
			});
		}
		if (window.addthis){
		    window.addthis = null;
		}
	},
	loadSite: function (page, id, cid, pid) {
		var url = "/index.php";
		if(!((page == "images") && ($("#images-page").length))){
			Site.removeContent();
		}
		else {
			$(".photo-item:visible").fadeOut(400);
		}
		var dataObj = {
				page: page,
				ajax: 1,
				cid : cid,
				pid : pid,
				id : id
			};
		$.ajax({
			url: url,
			global: false,
			type: "GET",
			data: dataObj,
			dataType: "html",
			async: false,
			success: function (data) {
				var t = 0;
				if($("section").length){
					t = 300;
				}
				setTimeout(function(){
					if((page == "images") && ($("#images-page").length) && (cid != "bio")){
							$("section").removeClass("video-page").html(innerShiv($("section", data).html(), false));
							$(".photo-item").hide().fadeIn(400);
					}
					else {
					$("section").remove();
					$("header").after(innerShiv($("div", data).html(), false));
					$("section").hide().fadeIn(600);
					}
					document.title = $("h1",data).html()+" - I LIKE PHOTO Group";		
					Site.init();
					
				},t);
			}
		});
	},
	cleanonChange: function () {
		$(".loader").remove();
	},
	doAddThis : function(){		
		var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
		if (window.addthis){
		    window.addthis = null;
		}
		$.getScript( script );
	}
};
var Images = {
	init : function(){
		if($(".photo-thumbs li").length){
			$(".photo-thumbs li").unbind()
			.bind("mouseover",Images.thumbOver)
			.bind("mouseout",Images.thumbOut);
		}
		if($(".p-pdf").length){
			$(".p-pdf").unbind().bind("click",Images.addToPdf);
		}
	},
	thumbOver : function(e){
		var w = 400 - $(e.currentTarget).width(),
		$t = $(e.currentTarget).not(".selected");
		$t.find("img").css("opacity",1).animate({"opacity":0.6},300);
		$t.stop(true,false).css({backgroundPosition : "-400px 0px"}).animate({backgroundPosition : "-"+w+"px 0px"},500, "easeOutQuad");
	},
	thumbOut : function(e){
		var w = $(e.currentTarget).width(),
		$t = $(e.currentTarget).not(".selected");
		$t.find("img").css("opacity",0.6);
		$t.stop(true,false).animate({backgroundPosition : w+"px 0px"},750, "easeOutQuad", function(){$t.find("img").animate({"opacity":1},300);});
	},
	addToPdf : function(e){
		e.preventDefault();
		var file = $(".photo-item:visible img").attr("src");
		file = file.split("/");
		var filename = file[file.length-1].replace(".jpg","");
		Pdf.add(filename);
	},
	jump : function(dir){
		var goTo, $next, $prev, $thumbs = $(".photo-thumbs"), $current = $thumbs.find("li.selected");
		if(dir==1){
			$next = $current.next();
			if($next.length) goTo = $next.find("a").attr("href"); else  goTo = $thumbs.first().find("a").attr("href"); 
		}
		else {
			$prev = $current.next();
			if($prev.length) goTo = $prev.find("a").attr("href"); else  goTo = $thumbs.last().find("a").attr("href");
		}
		$.address.value(goTo);
	}
};
var KeyNav = {
  keyup : function(event) {
    if (event.keyCode == 37) {
	if($("#photo-frame").length){
            Images.jump(-1);
        }
  } else if (event.keyCode == 39) {
	if($("#photo-frame").length){
             Images.jump(1);
        }
  }
  }
}
var Pdf = {
	init : function(){
		if($.cookie('pdfString')){
			$("#o5 a").html("Your pdf ["+$.cookie('pdfCount')+"]");
		}
		else {
			$.cookie('pdfString', '');
			$.cookie('pdfCount', 0);
		}
	},
	add : function(f){
		var c = $.cookie('pdfString');
		var l = Number($.cookie('pdfCount'));
		if(c != '') c+= "|";
		c += f;
		$.cookie('pdfString', c);
		l++;
		$.cookie('pdfCount', l);
		Pdf.updateCount(l);
		$(".p-pdf").fadeOut(300);
		Pdf.movePdf(f);
	},
	updateCount : function(n){
		var $o = $("#o5"),
		blink = function(t) {
			setTimeout(function(){$o.css({opacity : 0.5})},t);
			setTimeout(function(){$o.css({opacity : 1})},t+500);
		}
		$o.find("a").html("Your pdf ["+n+"]");
		for(var i = 0; i<4; i++){
			var lock = function(){return i};
			blink(lock()*1000);
		}
	},
	movePdf : function(f){
		var $pIv = $(".photo-item:visible"),
		sLeft = $pIv.offset().left + $pIv.width()/2,
		sTop = $pIv.offset().top + $pIv.height()/3,
		tLeft = $("#o5").offset().left,
		tTop = $("#o5").offset().top,
		css = {  position : "absolute",  zIndex : 500, display : "block", opacity : 0.5, height : 80+"px", left : sLeft + "px", top : sTop + "px" },
		img = '<img id="move" src="/media/photos/icon/'+f+'.jpg" alt="" />';
		$("body").append(img);
		$('html,body').animate({scrollTop:0}, 400);
		$("#move").css(css)
		.animate({left : tLeft + "px", top : tTop + "px"}, 1000, "easeOutQuad",  function(){$(this).animate({opacity : 0},400).delay(1).remove()});
	},
	drawPdf : function(){
		var p = $.cookie('pdfString').split("|"), h = "";
		if($.cookie('pdfString') != ""){
			$.each(p, function(a,b){
				h += '<li class="'+b+'"><img src=" /media/photos/icon/'+b+'.jpg" alt="" /><a href="#">x</a></li>';
			});
			h = '<section id="pdf"><h1>Your pdf</h1><a href="#" id="pdf-download">download</a><ul id="pdf-list">'+h+'</ul></section>';
		}
		else {
			h = '<section id="pdf"><h1>Your pdf</h1>Add images to the pdf while browsing the portfolios.</section>';
		}
		return h;
	},
	initSorting : function(){
		$("#pdf-download").unbind().bind("click",Pdf.download);
		$("#pdf-list").sortable()
		.disableSelection()
		.bind("sortstop",Pdf.onSortStop);
		$("#pdf-list a").unbind().bind("click",Pdf.deletePage);
	},
	deletePage : function(e){
		e.preventDefault();
		$(e.currentTarget).parent().animate({width : 0},function(){$(this).remove(); Pdf.onSortStop(); Pdf.updateCount($("#pdf-list").find("li").length);});
		
	},
	onSortStop : function(){
		var s ="", c = 0;
		$("#pdf-list").find("li").each(function(a,b){
			c++;
			s+="|"+$(b).attr("class");
		});
		s = s.substring(1);
		$.cookie('pdfString', s);
		$.cookie('pdfCount', c);
	},
	download : function(e){
		e.preventDefault();
		Pdf.createForm("printpdf/index.php",$.cookie('pdfString'));
	},
	createForm : function(path, box) {  
		var method = "post",
		form = document.createElement("form"),
		hiddenField = document.createElement("input");
		form.setAttribute("method", method);
		form.setAttribute("action", path);
		form.setAttribute("target", "_blank");  
		hiddenField.setAttribute("type", "hidden");
		hiddenField.setAttribute("name", "box");
		hiddenField.setAttribute("value",box);
		form.appendChild(hiddenField);
		document.body.appendChild(form);    
		form.submit();
		document.body.removeChild(form);  
	}
};
var Ftp = {
	init: function () {
		if ($("#ftplogin").length) $("#ftplogin").submit(Ftp.onsubmit);
	},
	onsubmit: function () {
		var forms = $("#ftplogin").find("input");
		var str = "username=" + $(forms[0]).val() + "&pass=" + $(forms[1]).val();
		$.post("ftp/login.php", str, Ftp.postftp);
		return false;
	},
	postftp: function (data, textStatus) {
		if (data == "OK") {
			$("#files").load("ftp/list.php", function () {
				$("#files").fadeIn("fast").find("ul ul").hide();
			});
		} else {
			alert("Wrong username or password. Please try again.");
		}
	},
	toggle: function (i, f) {
		if (f != undefined) {
			$("#ul" + i + "_" + f).slideToggle();
		} else {
			$("#ul" + i).slideToggle();
		}
	}
};
var Chimp = {
	init: function () {
		var f = $("#chimp");
		if(f.length) $(f).unbind().bind("submit",Chimp.onSubmit);
	},
	onSubmit: function (e) {
		e.preventDefault();
		var f = $("#chimp"),
		str = $(f).serialize();
		console.log(str);
		$.post("chimp/index.php", str, function (data, textStatus) {
			if (data == "SENT") {
				if($("p.chimp").length) $("p.chimp").remove();;
				$(f).slideUp(600)
				.after("<p class='chimp' style='display: none;'>Thank you. Please confirm your subscription by clicking on the link in the e-mail we have just sent you.</p>");
				$("#subscribe p:not(:visible)").slideDown(600);
			} else {
				if($("p.chimp").length) $("p.chimp").remove();;
				$(f).after("<p class='chimp' style='display: none;'>"+data+"</p>");
				$("#subscribe p:not(:visible)").fadeIn(600);
			}
		});
	}
};
var Flash = {
	flashvars : {},
	params : {
		quality : "best",
		scale : "noscale",
		salign : "tl",
		wmode : "transparent",
		allowfullscreen : "true",
		allowScriptAccess : "always"
	},
	
	attributes : {
		id: "full",
		name: "full"
	},
	
	init : function(){
		swfobject.embedSWF("swf/video.swf?v=2", "full", "100%", "100%", "10.0.0", "swf/expressInstall.swf", Flash.flashvars, Flash.params, Flash.attributes);
	}
}

$.address.change(Site.onChange);
$.address.init(Site.init);

$.extend({
	URLEncode: function (c) {
		var o = '';
		var x = 0;
		c = c.toString();
		var r = /(^[a-zA-Z0-9_.]*)/;
		while (x < c.length) {
			var m = r.exec(c.substr(x));
			if (m != null && m.length > 1 && m[1] != '') {
				o += m[1];
				x += m[1].length;
			} else {
				if (c[x] == ' ') o += '+';
				else {
					var d = c.charCodeAt(x);
					var h = d.toString(16);
					o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
				}
				x++;
			}
		}
		return o;
	}
});
$.extend($.easing, {
            easeOutQuad: function (x, t, b, c, d) {
            return -c *(t/=d)*(t-2) + b;
}});

/**
 * @author Alexander Farkas
 * v. 1.22
 */
(function(a){function d(a){a=a.replace(/left|top/g,"0px");a=a.replace(/right|bottom/g,"100%");a=a.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");var b=a.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);return[parseFloat(b[1],10),b[2],parseFloat(b[3],10),b[4]]}if(!document.defaultView||!document.defaultView.getComputedStyle){var b=a.curCSS;a.curCSS=function(a,c,d){if(c==="background-position"){c="backgroundPosition"}if(c!=="backgroundPosition"||!a.currentStyle||a.currentStyle[c]){return b.apply(this,arguments)}var e=a.style;if(!d&&e&&e[c]){return e[c]}return b(a,"backgroundPositionX",d)+" "+b(a,"backgroundPositionY",d)}}var c=a.fn.animate;a.fn.animate=function(a){if("background-position"in a){a.backgroundPosition=a["background-position"];delete a["background-position"]}if("backgroundPosition"in a){a.backgroundPosition="("+a.backgroundPosition}return c.apply(this,arguments)};a.fx.step.backgroundPosition=function(b){if(!b.bgPosReady){var c=a.curCSS(b.elem,"backgroundPosition");if(!c){c="0px 0px"}c=d(c);b.start=[c[0],c[2]];var e=d(b.end);b.end=[e[0],e[2]];b.unit=[e[1],e[3]];b.bgPosReady=true}var f=[];f[0]=(b.end[0]-b.start[0])*b.pos+b.start[0]+b.unit[0];f[1]=(b.end[1]-b.start[1])*b.pos+b.start[1]+b.unit[1];b.elem.style.backgroundPosition=f[0]+" "+f[1]}})(jQuery)
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};
