/**
 * Parse the standard value returned
 * from all MediaVault ajax calls.
 * 
 * This function is needed because
 * of the format all returned values
 * must be.
 * 
 * @param string msg The return data
 * from the ajax call
 */
function MV_parseAjaxMsg(msg)
{
	
	returnValue	= msg.substr(6, (msg.length - 6));
	return returnValue;
	
}

if (typeof console == "undefined" || typeof console.log == "undefined")
{
	
	var console = {
		log: function() {}
	};

}

/**
 * This function logs your message to console.
 * 
 * @param msg
 */
function MV_clog(msg)
{

	var d = new Date;
	
	var month = new Array(12);
	month[0] = "01";
	month[1] = "02";
	month[2] = "03";
	month[3] = "04";
	month[4] = "05";
	month[5] = "06";
	month[6] = "07";
	month[7] = "08";
	month[8] = "09";
	month[9] = "10";
	month[10] = "11";
	month[11] = "12";
	
	var minute = ( d.getMinutes() < 10 ) ? "0" + d.getMinutes() : d.getMinutes();
	var second = ( d.getSeconds() < 10 ) ? "0" + d.getSeconds() : d.getSeconds();
	
	var time = d.getFullYear() + "-" + month[d.getMonth()] + "-" + d.getDate() + " " + d.getHours() + ":" + minute + ":" + second + "." + d.getMilliseconds();
	
	console.log("[" + time + "] " + msg);
	
}


/**
 * AJAX error handling
 */
var ajaxErrors = "";
var ajaxErrorCount = 0;


/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {

		l++;

		for (i = 0; i < l; i++) {
			tab += sep;
		}

		if (x && x.length) {
			t = 'array';
		}

		r += '(' + t + ") :\n";

		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}

	} else {

		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}

		r += '(' + t + ') ' + x + "\n";

	}

	return r;

};
var_dump = print_r;

function MV_ajaxError(text, xhr)
{

    ajaxErrorCount++;
	
    ajaxErrors = ajaxErrors + "#" + ajaxErrorCount + "<br />";
    ajaxErrors = ajaxErrors + xhr.status + ", " + xhr.statusText + "<br />";
    ajaxErrors = ajaxErrors + text + "<br />"; 
    //ajaxErrors = ajaxErrors + xhr.responseText;
    ajaxErrors = ajaxErrors + "<br />";
    
    msgForLog = xhr.status + ", " + xhr.statusText + "::" + text;
    
    /*$.post("lib/ajax/ajaxError.php?msg=" + msgForLog, function(data) {

    	//alert("Error: " + data);
    	
    });*/
    
	$.ajax({
		
		type: "POST",
		url: "lib/ajax/ajaxError.php",
		data: "msg=" + msgForLog,
		success: function(data){

			//var returnData = MV_parseAjaxMsg(data);
			
		},
		global: false,
		error: function(data){

			var msg = "Error in AJAX error reporting<br />" + msgForLog;
			
			if ( PHP_SITE_LIVE == 0 )
			{
				alert(msg);
				MV_clog(msg);
			}

		}
	
	});
    
}

$(document).ajaxError( function(XMLHttpRequest, textStatus, errorThrown){
	
	MV_ajaxError(textStatus.status + ", " + textStatus.statusText, XMLHttpRequest);
    
});

$(document).ajaxStart( function() {

	//MV_clog("ajaxStart");
	
});

$(document).ajaxComplete( function (event, xhr, ajaxOptions) {
	
	//alert( var_dump(xhr, 2) );
	//alert(":" + ajaxOptions.processData);
	
	response = xhr.responseText;

	if ( response.substr(0,11) == "NOTLOGGEDIN")
	{
		
		var msg = "PHP error occured during ajax call in<br />URL: " + ajaxOptions.url + "<br /><br />" + response;
		
		if ( PHP_SITE_LIVE == 0 )
		{
			alert(msg);
			MV_clog(msg);
		}
		
		location.href = "admin/";
		
	}
	else if ( response.substr(0,6) !== "AJAXOK")
	{
		
		var msg = "PHP error occured during ajax call in<br />URL: " + ajaxOptions.url + "<br /><br />" + response;
		
		if ( PHP_SITE_LIVE == 0 )
		{
			
			alert(msg);
			MV_clog(msg);
			
		}
		
	}
	
});


$(document).ajaxStop( function (msg) {
	
	if (ajaxErrorCount > 0)
	{

		ajaxError = "An ajax error occurred<br /><br />" + ajaxErrors;
		//alert(ajaxError);
		
	}
	
	//MV_clog("ajaxComplete");
	
});

/**
 * AJAX Loading stuff
 */

jQuery.fn.MV_ajaxLoader = function(remove)
{

	$(this).each( function() {

		th = $(this);
		
		divAjaxLoader = "<div class=\"MV_ajaxLoader\" style=\"z-index: 400;position: absolute;padding: 20px 30px 20px 30px;background-color: #000000;\">";
		divAjaxLoader = divAjaxLoader + "<img src=\"siteadmin/img/ajax-loader.gif\" alt=\"\" title=\"\" />";
		divAjaxLoader = divAjaxLoader + "</div>";
		
		if (remove === true)
		{
		
			$(".MV_ajaxLoader").remove();
			
		}
		else
		{

			th.prepend(divAjaxLoader);
			$(".MV_ajaxLoader").corner("");
			
		}
		
	});
	
}

$(document).ready( function() {

	$("a[rel^='prettyPhoto']").prettyPhoto({theme : 'light_square'});
	
	$.fn.prettyPhoto({
		
		theme : 'light_square'
		
	});
	/*
	$.prettyLoader({
		
		bind_to_ajax : true,
		loader : 'css/images/prettyLoader/ajax-loader.gif'
		
	});
	*/
});

function imagePopupGallery(images, th, titles, descriptions)
{

	var index = $(th).attr("rel").replace("imagePopupGallery_", "");
	
	$.prettyPhoto.open(images, index);
	
}

function MV_login(loginError)
{

	var login_error = loginError;
	
	$.post("siteadmin/template/login.tpl.php?login_error=" + login_error, function(data) { 
		
		template = MV_parseAjaxMsg(data);
			
		$.prompt(template, {
			
			//show: "slideDown",
			buttons: { "Logga in" : true, "Avbryt" : 0 },
			prefix: "jqiwide",
			submit: function(v) {
				
				if (v)
				{
				
					$("#MV_loginForm").submit();
					
				}
				
			}
			
		});
		
	});
	
}

function MV_imagePopup(file_id)
{
	
	$.ajax({
		
		type: "POST",
		url: "lib/get/popup.php",
		data: "id=" + file_id,
		success: function(data){

			var returnData = MV_parseAjaxMsg(data);

			imageSrc = returnData.replace('<img src="', '').replace('" alt="" />', '');

			images = [imageSrc];
			$.prettyPhoto.open(images);
			
		}
	
	});

}

function MV_invite()
{
	
	$.post("CMS/template/inviteForm.tpl.php", function(data) { 
		
		template = MV_parseAjaxMsg(data);
			
		$.prompt(template, {
			
			buttons: { "Skicka" : true, "Avbryt" : 0 },
			//prefix: "jqiwide",
			submit: function(v, m, f) {
				
				if (v)
				{
				
					var sendData =	"from=" + f.invite_from + 
									"&from_email=" + f.invite_from_email +
									"&to=" + f.invite_to +
									"&to_email=" + f.invite_to_email +
									"&message=" + f.invite_message +
									"&url=" + escape(location.href);
						
					
					$.ajax({
						
						type: "POST",
						url: "CMS/ajax/sendInvite.php",
						data: sendData,
						success: function(data){

							var returnData = MV_parseAjaxMsg(data);

							//alert("data:" + returnData);
							
							alert("Ett mail har skickats till " + f.invite_to + " (" + f.invite_to_email + ")");
							
						}
					
					});
					
					
					
				}
				
			}
			
		});
		
	});
	
}

function MV_print()
{

	window.print();
	
}

function rgbToHex(rgb)
{

	if ( rgb.substr(0,1) == "#" )
	{

		return rgb;
		
	}

	if ( rgb == "transparent" )
	{

		return rgb;
		
	}
	
	//var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.
	var rgbString = rgb; // get this in whatever way.

	var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

	delete (parts[0]);
	
	for (var i = 1; i <= 3; ++i)
	{
		
	    parts[i] = parseInt(parts[i]).toString(16);
	    
	    if (parts[i].length == 1)
	    {
		    
			parts[i] = '0' + parts[i];

	    }
	    
	}
	
	var hexString = parts.join(''); // "0070ff"

	return "#" + hexString
	
}

