var removeAjaxEvents = function(){};
var actions = {
	multidownload: '0',
	download: '1',
	upload: '2',
	connection: '3',
	deconnection: '4',
	refresh: '5',
	loadPage: '6',
	saveConfig: '7',
	editFile: '8',
	editAccount: '9',
	deleteFile: 'a',
	changeCategory: 'd',
	changeStatus: 'e'
};

//hs.graphicsDir = 'images/highslideGraphics/';

var sep = '~|~';
var currentAction;
var userName = null;
var userId = null;
var imgRefreshCpt = 0;
var sessionOpened = false;
var thumbWidthMin = 110;
var userDate = getText('userDate');
var thumbWidthMax = 220;
var thumbWidthDelta = 20; // div around Thumbnails are 20px larger than images to show blank between images
var currentCallback;
var currentParams;
var extension = ".html";
var serverUrl = "/Photonization/";
var currentLoadTime = null;
var dTable = null;
var loadingTimeout;
var config = {
	"saveStats": true,
	"showLoadTimes": false,
	"ajaxMode": true,
	"toolTipEffect": ($.browser.chrome || ($.browser.msie && $.browser.version > 9)) ? "slide" : "toggle",
	"tableDisplayResults": 50,
	"slider": 170,
	"showThumbsTitle": false
};
var downloadBuffer = 0;
var mbContainerSkin = 'default';
var actionsJson = {actions: {}, code: 0}; // code is used as actionsId in client to server mode

$(document).ready(function (){
	
	$.historyInit(loadPage, "index.html");
	
	firstInit();
	
	$.reject({ // show popup if user navigator is old  
        //reject: { all: true }, // Reject all renderers for demo  
        reject: { 
        	msie5: true,
        	msie6: true,
        	msie7: true,
        	msie8: true,
        	firefox1: true,
        	firefox2: true,
        	firefox3: true,
        	firefox4: true
        },
        display: ['chrome', 'safari', 'msie'],
        browserInfo: {
	        chrome: {  
	            text: 'Chrome 12',  
	            url: 'http://www.google.com/chrome/'  
	        },  
	        safari: {  
	            text: 'Safari 5',  
	            url: 'http://www.apple.com/safari/download/'  
	        },
	        msie: {  
	            text: 'Internet Explorer 9',  
	            url: 'http://www.microsoft.com/windows/Internet-explorer/'  
	        }
        },
        closeCookie: true, // Set cookie to remember close for this session
        imagePath: serverUrl + 'images/browsers/',
        header: getText('header'),  
        paragraph1: getText('paragraph1'),  
        paragraph2: getText('paragraph2'),
        closeMessage: getText('closeMessage'),
        closeLink: getText('closeLink')
    }); 
	
	userMessage();
});

/*****************
 *     INIT
 ****************/


function firstInit(){
	
	userName = $('#userName').val();
	
	if (userName != null && userName != ""){ // Connected
		initUser(); // include initConfig && initHeader
	} else { // Not connected
		initHeader();
		if (config.ajaxMode)
			initLogin(); // include return false;
	}
}

function initHeader(){
	
	if (!$.browser.msie){
		$('#switcher').themeswitcher({
			width: 150, 
			height: 240, 
			initialText: getText('initialTextSwitcher')
		});
	}
	
	$('#fr, #en').click(function (){
		var href = this.href + window.location.hash;
		window.location.href = href;
		return false;
	});
};

/*****************
 *    LOGINS
 ****************/

function registerCallback(){
	$(".makeMeAbutton").button();
	registerValidator('#registerJson');
	$('input#name').focus();
}

function loginCallback(){
	$(".makeMeAbutton").button();
	loginValidator('#loginJson');
	$('#registerButton').click(function(){
		register();
		$('#loginContainer').close();
		return false;
	});
	$('input#nameLogin').focus();
}

function register(){
	$('#registerContainer').buildContainers();
	$('#registerContainer').mb_open('registerPageAjax' + extension, function(){
		$(".makeMeAbutton").button();
		registerValidator('#registerJson');
		return false;
	});
	return false;
};

function login(){ // called when connection button is clicked
	if (!config.ajaxMode) // ajaxMode false: initLogin is still not loaded so do it
		initLogin();
	else {
		var closed = $('#loginContainer').attr('closed');
		var iconized = $('#loginContainer').attr('iconized');
		
		if (closed != null){
			if (closed == 'true')
				$('#loginContainer').mb_show();
			else { // closed false
				if (iconized != undefined && iconized == 'true')
					$('#loginContainer').mb_iconize();
			}
		} else if (iconized != undefined && iconized == 'true') // close not defined
			$('#loginContainer').mb_iconize();
	}
	return false;
};

function initLogin(){ // called when page load if user is not logged && not ajaxMode 
	$('#loginContainer').buildContainers({
		containment:"document",
	    elementsPath:"images/mbContainer/",
	    onClose:function(o){},
	    onIconize:function(o){},
	    effectDuration:200
	});
	$('#loginContainer').mb_open('loginPageAjax' + extension, loginCallback);
	return false;
};

function disconnect(){
	$.ajax({
		type: 'POST',
		url: serverUrl + 'disconnectAjax' + extension,
		success: function(headerMenu){
			$('#content').empty();
			$('#outer-header').html(headerMenu);
			$.jGrowl('',{
				header: getText('Disconnected'),
				life:	5000,
				sticky: false
			});
			initMenu();
			initLogin();
			initHeader();
			$('#userName').val('');
			$('#userId').val('');
			$('#status').val('0');
			$('#adult').val('0');
		}, error: function(){
			$.jGrowl('',{
				theme: 	'error',
				header: getText("Error"),
				life:	5000,
				sticky: false
			});
		}
	});
	return false;
};

/*****************
 * 
 ****************/

function initMenu(){
	$(function(){
		$(".myMenu").buildMenu({
			menuWidth: 200,
			openOnClick: false,
			openOnRight: false,
			menuSelector: ".menuContainer",
			iconPath: "data/icons/",
			hasImages: true,
			fadeInTime: 100,
			fadeOutTime: 200,
			adjustLeft: 2,
			minZindex: "auto",
			adjustTop: 10,
			opacity: .95,
			shadow: true,
			closeOnMouseOut: true,
			closeAfter: 50000
		});
	});
	
	$('.container').hover(function(){
	    if ($f() != null)
	        $f().unload();
	});
	
	$("#filterCategoriesImg").tipTip({
		delay: 0,
		edgeOffset: 7,
		defaultPosition: "top"
	});
	
	$('#filterCategories').click(function(){
		refreshMenu();
	});
}

function selectPage(action, callback, params, adultCategory){
	
	if (adultCategory != undefined){
		if ($('#adult').val() == "0"){
			$.jGrowl('',{
				theme: 	'error',
				header: getText("AdultCategoryNeedLogin"),
				life:	12000,
				sticky: false
			});
			login();
			return false;
		} else if ($('#adult').val() == "1"){
			$.jGrowl('',{
				theme: 	'error',
				header: getText("AdultCategoryNeedBirthday"),
				life:	12000,
				sticky: false
			});
			editAccount("editUserAjax" + extension + "?id=" + $('#userId').val(), function(){
				$.ajax({
					type: 'POST',
					async: false,
					url: serverUrl + 'updateAdultStatusJson' + extension,
					success: function(json){
						if (json.code == 0){
							$('#adult').val(json.message);
							if (json.message != 3)
								$.jGrowl('',{
									theme: 	'warning',
									header: getText("NotAccessAdult"),
									life:	10000,
									sticky: false
								});
						} else if (json.code == 1){
							$('#adult').val(json.message);
							$.jGrowl('',{
								theme: 	'error',
								header: "Error",
								life:	5000,
								sticky: false
							});
						}
					}, error: function(){
						$.jGrowl('',{
							theme: 	'error',
							header: "Error",
							life:	5000,
							sticky: false
						});
					}
				});
			});
			return false;
		} 
		if ($('#adult').val() == "2"){
			$.jGrowl('',{
				theme: 	'error',
				header: getText("AdultCategoryNotAccess"),
				life:	12000,
				sticky: false
			});
			return false;
		}
		// 3 = ok
	}
	
	if (config.ajaxMode)
		$.historyLoad(action, callback, params);
	else {
		var url;
		if (params != undefined)
			url = serverUrl + action + extension + "?" + params;
		else 
			url = serverUrl + action + extension;
		location.href = url;
	}
}

// example : loadPage('thumbnail', videosThumbnails, 'category=humor'){
function loadPage(action, callback, params){
	if (userName != null && userName != "" && actionsJson.code == 0){ // get a new actionsId
		$.ajax({
			type: 'POST',
			async: false,
			url: serverUrl + 'getActionsIdJson' + extension,
			success: function(json){
				actionsJson.code = json.code;
			}
		});
		if (actionsJson.code == 0){
			$.ajax({
				type: 'POST',
				async: false,
				url: serverUrl + 'getActionsIdJson' + extension,
				success: function(json){
					actionsJson.code = json.code;
				}
			});
		}
	}
	sessionOpened = true;
	currentAction = action;
	currentCallback = callback;
	currentParams = params;
	
	// dataParams example : category=humor&json={....}
	var	dataParams = (params != undefined ? params + "&" : "");
	
	// jsonParams example : action=thumbnail~|~callback=videosThumbnails~|~category=humor
	var jsonParams = "action=" + action + ((callback != undefined && callback != null) ? sep + "callback=" + getFunctionName(callback) : "") + (params != undefined ? sep + "params=" + params : "");
		
	if (actionsJson.actions[actions.loadPage] == undefined)
		actionsJson.actions[actions.loadPage] = [];
	actionsJson.actions[actions.loadPage].push([new Date().getTime(), jsonParams, 0]);
	var jsonString = $.toJSON(actionsJson);
	while (jsonString.indexOf("&") != -1)
		jsonString = jsonString.replace("&", "|~*~|");
	dataParams += "json=" + jsonString;
	
	if(config.ajaxMode && action != "") {
		var timeBefore = new Date().getTime();
		$.ajax({
			type: 'POST',
			url: serverUrl + action + 'Ajax' + extension,
			data: dataParams,
			success: function(msg){
				updateActionJson();
				_gaq.push(['_trackPageview', action,  getValueFromParameter(params)]);
				$('#content').html(msg);
				if (callback != undefined && callback != null)
					callback(params);
				if (config.saveStats){
					var loadTime = sep + "LoadTime=" + currentLoadTime + sep + "browserName=" + $.browser.name + sep + "browserVersion=" + $.browser.version + sep + "os=" + navigator.platform;
					var loadPage = actionsJson.actions[actions.loadPage];
					if (loadPage[loadPage.length - 2] != undefined){
						var lastLoadPage = loadPage[loadPage.length - 2][1];
						actionsJson.actions[actions.loadPage][loadPage.length - 2][1] = lastLoadPage + loadTime;
					}
					if (config.showLoadTimes){
						var timeAfter = new Date().getTime();
						var time = timeAfter - timeBefore;
						currentLoadTime = time;
						$.jGrowl('',{
							header: showLoadTimes(time),
							life:	5000,
							sticky: false
						});
					}
				}
				else {
					if (config.showLoadTimes){
						var timeAfter = new Date().getTime();
						currentLoadTime = timeAfter - timeBefore;
						$.jGrowl('',{
							header: showLoadTimes(time),
							life:	5000,
							sticky: false
						});
					}
				}
				updateActionJson();
				cleanDownloadsActionJson();
			},
			error: function(msg){
				$.jGrowl('',{
					theme: 	'error',
					header: getText("Error"),
					life:	3000,
					sticky: false
				});
			},
			beforeSend: function(msg){
				removeAjaxEvents();
				removeAjaxEvents = function(){};
				$('#content').empty();
				$('#footer').hide();
				loadingTimeout = setTimeout("$('#loading').show();", 300);
			},
			complete: function(msg){
				clearTimeout(loadingTimeout);
				$('#loading').hide();
				$('#footer').show();
			}
		});
	} else if (action != ""){
		var url = serverUrl + action + extension;
		if (params != undefined && params != "")
			url += "?" + params;
		location.href = url;
	}
}

function userMessage(){
	$("#userMessage").tipTip({
		delay: 0,
		edgeOffset: 7,
		defaultPosition: "top"
	});
	$('#userMessage').click(function(){
		
		if ($('#userId').val() == "" || $('#userId').val() == "0"){
			$.jGrowl('',{
				theme: 	'error',
				header: getText("needLoginForPostMEssage"),
				life:	12000,
				sticky: false
			});
			login();
			return false;
		}
		
		var containerId = "";
		containerId = createMbContainer('#userMessageContainer', "userMessageContainer", containerId);
		
		$(containerId).mb_open('userMessagePageAjax' + extension, function(){
			$(".makeMeAbutton").button();
			
			$('#submitUserMessage').click(function(){
				$.ajax({
				   type: "POST",
				   url: 'writeUserMessageJson' + extension,
				   dataType: 'json',
				   data: {userMessage: $('#userMessage').val()},
				   success: function(json) {
					  if (json == 1){
						  $.jGrowl('',{
								theme: 	'error',
								header: json.message,
								life:	5000,
								sticky: false
						  }); 
					  } else { 
						  $.jGrowl('',{
								theme: 	'success',
								header: getText('MessageSaved'),
								life:	5000,
								sticky: false
							});
						  $(containerId).mb_close();
					  }
				   },
				   error: function(json){
					   	$(containerId).mb_close();
					   	$.jGrowl('',{
							theme: 	'error',
							header: getText('Error'),
							life:	5000,
							sticky: false
						});
				   }
				});
			});
			
			$('#cancelUserMessage').click( function (){
				$(containerId).mb_close();
				return false;
			});
		});
		$(containerId).css('top', (getScrollPosition()[1] + 100) + 'px');
		return false;
	});
}

/*****************
 *   PAGE AJAX
 ****************/

function removeCell(cell){
	if(cell == undefined || cell == null)
		return;
    while (cell.childNodes.length >= 1){
        cell.removeChild(cell.firstChild);       
    }
}

function removeChildrenRecursively(node){
	if (!node) 
		return;
	while (node.hasChildNodes()){
		removeChildrenRecursively(node.firstChild);
		node.removeChild(node.firstChild);
	}
}

function showLoadTimes(time){
	var message = "";
	message += getText('LoadTime') + ': ' + time + " ms<br />";
	if (actionsJson.actions[actions.loadPage] != undefined)
		message += getText('PagesVisited') + ': ' + actionsJson.actions[actions.loadPage].length + "<br />";
	if (actionsJson.actions[actions.download] != undefined)
		message += getText('Downloads') + ': ' + actionsJson.actions[actions.download].length + "<br />";
	if (actionsJson.actions[actions.multidownload] != undefined)
		message += getText('MultiDownloads') + ': ' + actionsJson.actions[actions.multidownload].length + "<br />";
	if (actionsJson.actions[actions.upload] != undefined)
		message += getText('Uploads') + ': ' + actionsJson.actions[actions.upload].length + "<br />";
	message += '<a href="#" onclick="selectPage(\'account\', account); return false;">' + getText('MoreDetails') + '</a>';
	return message;
}
