/***********************************************************************
 * 
 *  JavaScript Functions for eve publisher / cms.
 *  copyright eve-images.com, Berlin 2010
 *  
 * *********************************************************************/






var loggedIn = false;

$(document).ready(function () {
	$.ajaxSetup ({
	    // Disable caching of AJAX responses
	    cache: false
	});

	initializeEveCms();	
	//jqmToIFrame();
});



// initialize function contains all intitializations

initializeEveCms = function () {

	// append append hidden modal div for tinyMCE to the bottom
	$('body').prepend('<div id="modalWindow" class="jqmWindow"><form><p><textarea id="contentEditor" name="content" cols="50" rows="20"></textarea><br/><input type="button" value="Save" id="editSave"/><input type="button" value="Cancel" onclick="$(\'#modalWindow\').jqmHide()"/></p></form></div>');
	
	window.onresize = adjustModalPosition;

	/*
	if ($('#adminPanel').length == 0) {
		$('#eve_menu').css('display', 'none');
	} 
	//alert('init eve cms');
	// init eve admin panel
	$('#addi').click(function () {
		$('#eve_menu').slideToggle('fast');
	});
	*/
	$('#loginForm input').bind('keypress', function(e) {
        if(e.keyCode==13){
                // Enter pressed
        	handleLogin();
        }
	});

	
	$("#loginSubmit").click(function(){
		handleLogin();
	});
	
	// INIT EXTENDED BACKEND FUNCTIONALITY - each submenu part get loaded per ajax
	
	$('#eve_settings').click(function () {
		editSettings();
		/*
		if( $('#eve_extended').is(':visible') ) {
	        // code to run if visible
			$('#eve_extended').load('evecms/template/admin/settings.eve', function () {
				initCloseButton();
			});
	    } else {
	        // code to run of not visible
	    	$('#eve_extended').slideToggle('fast',  function() {	
				$('#eve_extended').load('evecms/template/admin/settings.eve', function () {
					initCloseButton();
				});
			 });
	    }
	    */
	});
	$('#eve_pages').click(function () {
		if( $('#eve_extended').is(':visible') ) {
	        // code to run if visible
			$('#eve_extended').load('evecms/template/admin/pages.eve', function () {
				initCloseButton();
			});
	    } else {
	        // code to run of not visible
	    	$('#eve_extended').slideToggle('fast',  function() {	
				$('#eve_extended').load('evecms/template/admin/pages.eve', function () {
					initCloseButton();
				});
			 });
	    }
	});
	$('#eve_news').click(function () {	
		if( $('#eve_extended').is(':visible') ) {
	        // code to run if visible
			$('#eve_extended').load('evecms/template/admin/news.eve', function () {
				initCloseButton();
			});
	    } else {
	        // code to run of not visible
	    	$('#eve_extended').slideToggle('fast',  function() {	
				$('#eve_extended').load('evecms/template/admin/news.eve', function () {
					initCloseButton();
				});
			 });
	    }
	});
	$('#eve_files').click(function () {	
		if( $('#eve_extended').is(':visible') ) {
	        // code to run if visible
			$('#eve_extended').load('evecms/template/admin/files.eve', function () {
				initCloseButton();
			});
	    } else {
	        // code to run of not visible
	    	$('#eve_extended').slideToggle('fast',  function() {	
				$('#eve_extended').load('evecms/template/admin/files.eve', function () {
					initCloseButton();
				});
			 });
	    }
	});

	
	$('.logout_link').click(function () {
		$.ajax({
			url: 'evecms/core/logout.php',
			success: function(data) {
			setMessage("you will be logged out.");
			//changeAdminPanelAfterLogout();
			setTimeout("$('#eve_extended').fadeOut('slow');$('#eve_menu').slideUp(400);", 800);
			setTimeout("location = 'index.php';", 1300);
		  	}
			});
	});
	
	// initialize jquery modal window (overlay)
	 $('#modalWindow').jqm({ajax:'evecms/core/edit.php?idcontent=1'});
	 
}

handleLogin = function () {
	var usr = $("#username").val();
	var pw = $("#password").val();
	$.ajax({
		url: 'evecms/core/login.php',
		type: "POST",
		dataType: 'text',
		data: {username: usr, password: pw},
		error: function (xhr, status) {
        alert(status);
    	},
    	success: function (data) {
    		if(jQuery.trim(data) != "true") {
				$("#loginStatus").fadeIn().animate({opacity: 1.0}, 500).fadeOut(2000);
				$("#loginStatus").html('<div class="ajax_error" style="color: red;">login / password wrong</div>');
				$("#username").val('');
				$("#password").val('');
			}
			else {
				$("#loginStatus").fadeIn().animate({opacity: 1.0}, 500).fadeOut(2000);
				$("#loginStatus").html('<div class="ajax_accept" style="color: green;">you are now logged in.</div>');
				setTimeout('changeAdminPanelAfterLogin();', 1000);
				setTimeout('location.reload();', 1100);
			}

    	}
	});
	
}


function initCloseButton() {
	$("#eve_close").click(function(){
		$('#eve_extended').slideUp('slow');
	});
}


function delete_news(news_id) {
	var confirm_delete = confirm("are you sure you want to delete this news?");
	if (confirm_delete) {
		$.ajax({
			url: 'evecms/core/news/deleteNews.php',
			type: "POST",
			dataType: 'text',
			data: {idnews: news_id},
			error: function (xhr, status) {
	        alert(status);
	    	},
	    	success: function (data) {
	    		if(data == 1) {
					alert("news deleted!");
					$('#modalWindow').jqmHide();
					location.reload();
				}
				else {
					alert("problem updating db.");
				}

	    	}
		});
	}
}

function editItem(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/edit.php?idcontent='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}

function editSettings()
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/editSettings.php'});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}

function editFiles()
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/editFiles.php'});
	
	setTimeout("$('#modalWindow').jqmShow();", 100);
		 
}

function editNews(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/news/editNews.php?idnews='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}

function editNewsImage(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/news/editNewsImage.php?idnews='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}
function addSubPage(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/addSubpage.php?pageid='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}
function unlinkPage(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/unlinkPage.php?pageid='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}
function editPage(id)
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/editPage.php?pageid='+id});
	setTimeout("$('#modalWindow').jqmShow();", 100);
}
function addNews()
{
	$('#modalWindow').jqm({ajax:'evecms/core/admin/addNews.php'});
	setTimeout("$('#modalWindow').jqmShow();", 100);
	
	
}
function ajaxFileUpload()
{

	$.ajaxFileUpload
	(
		{
			url:'evecms/core/imgUpload.php',
			secureuri:false,
			fileElementId:'imgUploadForm',
			dataType: 'json',
			cache: 'false',
			beforeSend:function()
			{
				$("#loading").show();
			},
			complete:function()
			{
			 $("#loading").hide();
			}, 
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						alert(data.msg);
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}

function setMessage(msg)
{
	$("#loginStatus").fadeIn().animate({opacity: 1.0}, 500).fadeOut(2000);
	$("#loginStatus").html('<div class="ajax_info">'+msg+'</div>');
}

function adjustModalPosition()
{
	var top = (window.innerHeight/2)-($('#modalWindow').height()/2);
	var left = (window.innerWidth/2)-($('#modalWindow').width()/2);
	//$('#modalWindow').animate({marginLeft: left+"px", marginTop: top+"px"}, 500);
	$('#modalWindow').css({marginLeft: left+"px", marginTop: top+"px"});
}


function jqmToIFrame() {
	var closeModal = function(hash)
	{
		var $modalWindow = $(hash.w);
		//$('#jqmContent').attr('src', 'blank.html');
		$modalWindow.fadeOut('2000', function()
		{
			hash.o.remove();
			//refresh parent
			if (hash.refreshAfterClose == true)
			{
				window.location.href = document.location.href;
			}
		});
	};
	var openInFrame = function(hash)
	{
		var $trigger = $(hash.t);
		var $modalWindow = $(hash.w);
		var $modalContainer = $('iframe', $modalWindow);
		var myUrl = $trigger.attr('href');
		var myTitle = $trigger.attr('title');
		var newWidth = 0, newHeight = 0, newLeft = 0, newTop = 0;
		$modalContainer.html('').attr('src', myUrl);
		$('#jqmTitleText').text(myTitle);
		myUrl = (myUrl.lastIndexOf("#")> -1) ? myUrl.slice(0, myUrl.lastIndexOf("#")) : myUrl;
		var queryString = (myUrl.indexOf("?")> -1) ? myUrl.substr(myUrl.indexOf("?") + 1) : null;
		if (queryString != null && typeof queryString != 'undefined')
		{
			var queryVarsArray = queryString.split("&");
			for (var i = 0; i <queryVarsArray.length; i++)
			{
				if (unescape(queryVarsArray[i].split("=")[0]) == 'width')
				{
					var newWidth = queryVarsArray[i].split("=")[1];
				}
				if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'height')
				{
					var newHeight = queryVarsArray[i].split("=")[1];
				}
				if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'jqmRefresh')
				{
					hash.refreshAfterClose = queryVarsArray[i].split("=")[1]
				} else
				{
					hash.refreshAfterClose = true;
				}
			}
			// let's run through all possible values: 90%, nothing or a value in pixel
			if (newHeight != 0)
			{
				if (newHeight.indexOf('%')> -1)
				{
					newHeight = Math.floor(parseInt($(window).height()) * (parseInt(newHeight) / 100));
				}
				var newTop = Math.floor(parseInt($(window).height() - newHeight) / 2);
			}
			else
			{
				newHeight = $modalWindow.height();
			}
			if (newWidth != 0)
			{
				if (newWidth.indexOf('%')> -1)
				{
					newWidth = Math.floor(parseInt($(window).width() / 100) * parseInt(newWidth));
				}
				var newLeft = Math.floor(parseInt($(window).width() / 2) - parseInt(newWidth) / 2);
			}
			else
			{
				newWidth = $modalWindow.width();
			}
			// do the animation so that the windows stays on center of screen despite resizing
			$modalWindow.css({
				width: newWidth,
				height: newHeight,
				opacity: 0
			}).jqmShow().animate({
				width: newWidth,
				height: newHeight,
				top: newTop,
				left: newLeft,
				marginLeft: 0,
				opacity: 1
			}, 'slow');
		}
		else
		{
			// don't do animations
			$modalWindow.jqmShow();
		}
	}
	$('#modalWindow').jqm({
		overlay: 70,
		modal: true,
		trigger: 'a.thickbox',
		target: '#jqmContent',
		onHide: closeModal,
		onShow: openInFrame
	});
}

