jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){
	//$("body").disableSelection();
	$("#st-user").focus(function(){
		if ($(this).val() == 'email'){
			$(this).select();
		}
	});
	$("#st-user").blur(function(){
		if ($(this).val() == ''){
			$(this).val('email');
		}
	});
	$("#st-pass").focus(function(){
		if ($(this).val() == 'password'){
			$(this).val("");
		}
	});
	$("#st-myaccount-link").click(function(){
		$(this).parent().animate({opacity: "0"},100).animate(
			{width:"hide",height:"hide"},100,'',function(){
				$("#st-login-form").show(300,function(){
					$("#st-login-form form").fadeIn(100,function(){
						$("#st-user").focus();
					});
			});
		});
		return false;
	});
	
	$("#inlineMessages a.close").click(function(){
		hideInlineMessage();
		return false;
	});
	
	$.ajaxSetup({
		url: "/ajax.php",
		global: false,
		type: "get",
		dataType: "json"
	});
	
	function showLoginError(err, color){
		$("#tlerr").remove();
		lf = $("#st-login-form"); 
		c = $("<div />").addClass("im").attr({id: 'tlerr'});
		l = lf.position().left; t = lf.position().top + lf.innerHeight() + 5;
		if (typeof color == 'undefined'){
			color = 'red';
		}
		c.css({position: 'absolute', top: t+'px', left: l+'px', color: color, width: '220px'});
		c.html(err).hide();
		lf.after(c); c.fadeIn("fast");
	}
	
	$("#st-login-form form").submit(function(){
		d = $(this);
		showLoginError('Logging in...', 'green');
		un = d.find("input[name='user']").val();
		psw = d.find("input[name='pass']").val();
		d.find("input").attr("disabled", true);
		$("<div />").userApi({
			page: 'autoLogin',
			username: un,
			password: psw,
			onError: function(err) {
				showLoginError(err);
				d.find("input").attr("disabled", false);
			},
			terminal: 'photosnack',
			onLogin: function(sId) {
				
				$.ajax({
					data: {page: 'login', sessionId: sId, loadLoginBox: true},
					success: function(d){
						$("#loginBox").html(d.res);
						$("#loginBox").hide();
						$("#loginBox").fadeIn("fast");
						$("#loginBox").show();
						$.userApi.sessionId = sId;
					}
				});
			}
		});
		return false;
	});
	/*
	if(location.pathname.replace(/\//gi, '') == 'my-account'){
		$("#userMenu a").each(function(){
			hr = $(this).attr("href");
			act = hr.split('#');
			if(act.length > 1){
				$(this).click(function(){
					$("#userMenu a").removeClass("selected");
					act = $(this).attr("href").split('#');
					act = act[act.length-1].split('.');
					if (act.length > 1) {
						$("#userApiCont").userApi({action: act[0], subpage: act[1]});
					} else {
						$("#userApiCont").userApi({action: act[0]});
					}
					$(this).addClass("selected");
					UA_onHideError();
				});
			}
		});
	}
	*/
});

function getLoadingImage()
{
	$loadingImg = $('<img />').attr({src: CDNPATH+'/images/loading.gif'});
	return $loadingImg; 
}

function handleErrors(code, res){
	showErrorMessage(res);
}

var $imTimeout;
var imInited = false;
function showInlineMessage($message, $type, $right, $time, $callback)
{
	if (!imInited){
		initMessages();
		imInited = true;
	}
	
	if ($type == 'err'){
		c = $("#inlineMessages .err");
	} else {
		c = $("#inlineMessages .not");
		if ($.cookie('ignallguidlines')){
			return;
		}
	}
	clearTimeout($imTimeout);
	c.find("div.right").html($right);
	c.find("div.left").html($message);
	
	if (typeof $message == 'object'){
		c.find("div.left").html($message);
		$message.show();
	} else {
		c.find("div.left").html($message);
	}
	
	if (c.css("display") == 'none'){
		c.slideDown(200);
	}
	c.find("a.close").click(_closeInlineMessage);
	if (c.find("a.ignore_all").length == 1){
		c.find("a.ignore_all").click(_ignoreAllGuidlines);
	}
	if (parseInt($time) > 0){
		$imTimeout = setTimeout("hideInlineMessage()",$time);
	}
	if ($(window).scrollTop() > $("#inlineMessages").position().top){
		$('html').animate({scrollTop: $("#inlineMessages").position().top}, 300);
	}
	
	if (typeof $callback == 'function'){
		$callback(im);
	}
}
function _ignoreAllGuidlines(){
	$.cookie('ignallguidlines', true, { expires: 10*365, path: '/' });
	hideInlineMessage($(this).parent().parent().parent().attr("class"), true);
}
function _closeInlineMessage(){
	hideInlineMessage($(this).parent().parent().parent().attr("class"), true);
}

function initMessages(){
	if ($("#inlineMessages").length >= 1){
		im = $("#inlineMessages"); 
	} else {
		im = $("<div />").attr({id: 'inlineMessages'});
		$("#master").before(im);
	}
	
	cont = $("<div />").addClass("cont");
	cont.append($("<div />").addClass("left"));
	cont.append($("<div />").addClass("right"));
	cont.append($("<br />").addClass("clear"));
	contErr = cont.clone();
	not = $("<div />").addClass("not").append(cont);
	err = $("<div />").addClass("err").append(contErr);
	im.html("");
	im.append(not).append(err);
}

function hideInlineMessage(t,userClicked)
{
	if (t && t == 'not') {
		if (typeof onGuidlineClose == 'function'){
			r = onGuidlineClose($("#inlineMessages .not"), userClicked);
			if (r == true){
				$("#inlineMessages .not").slideUp(200);
			}
		} else {
			$("#inlineMessages .not").slideUp(200);
		}
	} else {
		if (typeof onNoticeClose == 'function'){
			r = onNoticeClose($("#inlineMessages .not"), userClicked);
			if (r == true){
				$("#inlineMessages .not").slideUp(200);
			}
		} else {
			$("#inlineMessages .err").slideUp(200);
		}
	}
}
function hideGuidline()
{
	hideInlineMessage('not');
}
function showNotice(message, timeout, callback)
{
	showErrorMessage(message, timeout, callback);
}
function hideNotice()
{
	hideInlineMessage('err');
}
function hideAllMessages()
{
	hideInlineMessage('not');
	hideInlineMessage('err');
}
function showErrorMessage(message, timeout, callback)
{
	right = $("<a>").addClass("close").text("Dismiss").attr({href: '#'});
	showInlineMessage(message, 'err', right, timeout, callback);
}

function showMessage(message, timeout, callback)
{
	right = '<a href="#" class="close">Dismiss</a> <span style="color: #D2D2D2">|</span> <a href="#" class="ignore_all">Ignore all</a>'; 
	showInlineMessage(message, 'not', right, timeout, callback);
}

function validEmail(email)
{
	var regMail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (regMail.test(email)){
		return true;
	}
	return false;
}

function validScreenName(name)
{
	var regName = /^[0-9A-Za-z_\- ]+$/;
	if (regName.test(name)){
		return true;
	}
	return false;
}

function createAndOpenDownloadPopIn($hashId, $title, $albumHash, $albumWidth, $albumHeight)
{
	$time = 2000;
    $divToAdd ='<div id="dialog_download_'+$hashId+'" style="display:none; padding-top: 24px;">' +
				'<div id="previewFlash" style="width:600px; height: 480px; background-color: red;">' +
				'</div>' +
				'<input type="hidden" name="hash" class="hashtopass" value="'+$hashId+'"/>' + 
				'<div class="dialog_close_download_bigtitle">' +
					$title + 
				'</div>' +
			'</div>';
	$('body').append($divToAdd);

    $("#dialog_download_"+$hashId).dialog({
		bgiframe: false,
		modal: true,
		autoOpen: false,
		width: 656,
		height: 620,
		open: function() {
    		var hash = $(this).find(".hashtopass").val();
    		$(this).find('#previewFlash').flashembed({src:S3PHOTOSNACKURL+"/app/swf2/Download.swf?albumHash="+$albumHash+"&jobHash="+hash+"&embedWidth="+$albumWidth+"&embedHeight="+$albumHeight, bgcolor: "#141414", width:600, height:480});
			$parent = $(this).parent();
			$parent.find(".ui-dialog-buttonpane button:first").focus();

			$parent.find(".ui-dialog-titlebar").css('border-bottom', '1px solid #C6C6C6');
			$parent.find(".ui-dialog-titlebar").css('height', '41px');
			$closeSmall = $(this).find('div.dialog_close_download_bigtitle');
			if ($closeSmall.length > 0){
				$parent.find(".ui-dialog-titlebar").prepend($closeSmall);
			}

			//setTimeout("checkStatus('"+hash+"')", $time);
		},
		buttons: {
			Close: function(){
			
				hash = $(this).find(".hashtopass").val();
				//setTimeout("checkStatus('"+hash+"')", $time);
				$("#dialog_download_"+$hashId).dialog('close');
			}
		}
	});

    $("#dialog_download_"+$hashId).dialog('open');

}

function createIfNotExistsAndOpenDownloadPopIn($hashId, $title, $albumHash, $albumWidth, $albumHeight)
{
	$time = 2000;
	$popIn = $('#dialog_download_'+$hashId).html();
	if ($popIn == null)
	{
		alert('null');
	    $divToAdd ='<div id="dialog_download_'+$hashId+'" style="display:none; padding-top: 24px;">' +
					'<div id="previewFlash" style="width:600px; height: 480px; background-color: red;">' +
					'</div>' +
					'<input type="hidden" name="hash" class="hashtopass" value="'+$hashId+'"/>' + 
					'<div class="dialog_close_download_bigtitle">' +
						$title + 
					'</div>' +
				'</div>';
		$('body').append($divToAdd);
	
	    $("#dialog_download_"+$hashId).dialog({
			bgiframe: false,
			modal: true,
			autoOpen: false,
			width: 656,
			height: 620,
			open: function() {
	    		var hash = $(this).find(".hashtopass").val();
	    		$(this).find('#previewFlash').flashembed({src:S3PHOTOSNACKURL+"/app/swf2/Download.swf?albumHash="+$albumHash+"&jobHash="+hash+"&embedWidth="+$albumWidth+"&embedHeight="+$albumHeight, bgcolor: "#141414", width:600, height:480});
				$parent = $(this).parent();
				$parent.find(".ui-dialog-buttonpane button:first").focus();
	
				$parent.find(".ui-dialog-titlebar").css('border-bottom', '1px solid #C6C6C6');
				$parent.find(".ui-dialog-titlebar").css('height', '41px');
				$closeSmall = $(this).find('div.dialog_close_download_bigtitle');
				if ($closeSmall.length > 0){
					$parent.find(".ui-dialog-titlebar").prepend($closeSmall);
				}
	
				//setTimeout("checkStatus('"+hash+"')", $time);
			},
			buttons: {
				Close: function(){
				
					hash = $(this).find(".hashtopass").val();
					//setTimeout("checkStatus('"+hash+"')", $time);
					$("#dialog_download_"+$hashId).dialog('close');
				}
			}
		});
	}

    $("#dialog_download_"+$hashId).dialog('open');

}

function closeDownloadPopinAndCheckStatus($hashId)
{
	$time = 2000;
	$("#dialog_download_"+$hashId).dialog('open');
	setTimeout("checkStatus('"+$hashId+"')", $time);
}

/*function checkStatus($hashId)
{
	$.ajax({
		data: {
			page: 'check_download_status',
			hashId: $hashId
		},
		beforeSend: function() {
			loadImage = getLoadingImage();
			loadImage.css({width: '14px', height: '14px', 'float': 'left', margin: '0 0 0 35px'});
			$('#td_'+$hashId).html(loadImage);
		},
		complete: function() {
			
		},
		success: function(data) {
			if (data.code == 20){


				$status = data.res.status;
				$('#td_status_'+$hashId).html($status);
				if ($status == 'COMPLETE')
				{
					$('#td_'+$hashId).html(data.res.link);
					loadImage.remove();
				}
				else if($status == 'INITIAL')
				{
					$('#td_'+$hashId).html('<a href="#" onclick="openPopin(\''+$hashId+'\'); return false;" id="popin_{\''+$hashId+'\'}">Open popin</a>');
				}
				else
				{
					setTimeout("checkStatus('"+$hashId+"')", $time);
				}
				
				
			} else {
				showErrorMessage(data.res);
				loadImage.remove();
				$('#td_'+$hashId).html('<font style="color: red;">ERROR</font>');
			}
		}
	});
}*/


function aUA_onError(err){
	showErrorMessage(err);
}
function aUA_onNotice(err){
	showMessage(err);
}
function aUA_onHideError(){
	hideInlineMessage();
}
function UA_onLogout(){
	$.ajax({
		data: {page: 'logout'},
		success: function(){
			LOGGED = false;
			if (typeof(UA_onLogout2) == 'function') {
				UA_onLogout2();
			}
		}
	});
}
function UA_onLogin(sId){
	$.ajax({
		data: {page: 'login', sessionId: sId},
		success: function(){
			LOGGED = true;
			if (goToPageAfterLogin != '') {
				location.href = goToPageAfterLogin;
			}
		}
	});
}
function UA_ifLogged(sId){
	UA_onLogin(sId);
}
function UA_onRegister(user){
	$.ajax({data: {page: 'user_register', email: user.email, pass: user.password}});
}

function doActionOnBannerMaker() {
	if (LOGGED) {
		return true;
		
	} else {
		goToPageAfterLogin = '/banner-maker/software/';
		$.userApi.tellUserToLogin();
		return false;
	}
}

function doActionOnBuyPoints(goToAfterLogin)
{
	if (LOGGED)
	{
		$.userApi.buyPoints();
	}
	else
	{
		if (goToAfterLogin) {
			goToPageAfterLogin = goToAfterLogin;
		}
		$.userApi.tellUserToLogin();
	}
}
