/**
* SimpleUpdates Admin Javascript Functions
* 
* Contains functions used by core files
* 
* 
* This file is loaded on every page.
*/

/**
* We have to set the $su variable so we don't mess up some sites that use prototype or some other JS framwork that uses $
*/
var $su = jQuery;

var su_target_window;
function target_blank(url)
{
	var left = (screen.availWidth/2) - (450/2);
	var top = (screen.availHeight/2) - (300/2);
	su_target_window = window.open(url,'name','height=300,width=450,scrollbars=yes,left='+left+', top='+top);
	if (window.focus)
	{
		su_target_window.focus();
	}
}

function showThumbnailPicker()
{
	$su("img.delayLoad").trigger("loadImages");
	
	var vscroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	if(vscroll != 0) document.getElementById('uqwoho8hweh8we').style.top = vscroll + 'px';
	else document.getElementById('uqwoho8hweh8we').style.top = '0px';
	//alert(vscroll);
	
	document.body.style.overflow = "hidden";
	
	var availW;
	var availH;
	
	if (typeof window.innerWidth != 'undefined')
	{
	  availW = window.innerWidth,
	  availH = window.innerHeight
	}
	else if (typeof document.documentElement != 'undefined'
	 && typeof document.documentElement.clientWidth !=
	 'undefined' && document.documentElement.clientWidth != 0)
	{
	   availW = document.documentElement.clientWidth,
	   availH = document.documentElement.clientHeight
	}
	else
	{
	   availW = document.getElementsByTagName('body')[0].clientWidth,
	   availH = document.getElementsByTagName('body')[0].clientHeight
	}
	
	document.getElementById('doioer9efpoe').style.top = ((availH-425)/2) + 'px';
	if(vscroll != 0) document.getElementById('doioer9efpoe').style.top = (vscroll+((availH-425)/2)) + 'px';
	document.getElementById('doioer9efpoe').style.left = ((availW-460)/2) + 'px';
	
	document.getElementById('uqwoho8hweh8we').style.display = "block";
	document.getElementById('uqwoho8hweh8we').style.width = availW + 'px';
	document.getElementById('uqwoho8hweh8we').style.height = availH + 'px';
	
	document.getElementById('doioer9efpoe').style.position = "absolute";
	document.getElementById('doioer9efpoe').style.zindex = "1010";
	document.getElementById('doioer9efpoe').style.display = "block";
	document.getElementById('doioer9efpoe').style.visibility = "visible";
	document.getElementById('doioer9efpoe').style.opacity = "1";
	
	document.onkeydown = function ( e )
	{
		e = e || event || this.parentWindow.event ;
		if( e.keyCode == '27' ) // ESC
		{
			hideThumbnailPicker() ;
			return true ;
		}
	}
}
function hideThumbnailPicker()
{
	document.body.style.overflow = "auto";	
	//document.getElementById('uqwoho8hweh8we').style.display = "none";
	document.getElementById('doioer9efpoe').style.display = "none";
	document.getElementById('doioer9efpoe').style.visibility = "hidden";
	
}
function choose_thumbnail(thumbnailurl)
{
	if(thumbnailurl != "")
	{
		document.getElementById('thumbnail_div').innerHTML='<input type="hidden" name="thumbnailurl" value="'+thumbnailurl+'" /><a href="#" onclick="showThumbnailPicker(); return false;"><img src="'+thumb_path+thumbnailurl+'" height="50" width="40" border="1" style="border:1px solid black" /></a> <a href="#" onclick="showThumbnailPicker(); return false;"><? print _LANG_ARTICLEADMIN_THUMBNAIL_CHANGE; ?></a>';
	}
	else
	{
		document.getElementById('thumbnail_div').innerHTML='<input type="hidden" name="thumbnailurl" value="" /><a href="#" onclick="showThumbnailPicker(); return false;">'+select+'</a>';
	}
	
	hideThumbnailPicker();
	return false;
}

/**
* showFramelessDiv
* 
* @param string div The id of the div to display
*/
function showFramelessDiv(div)
{
	/*	Create the dark div	*/
	$su("body").append("<div class='su_frameless_div_back' id='su_frameless_div_back'></div>");
	$su("#su_frameless_div_back").show();
	
	var width = $su(window).width();
	$su("#su_frameless_div_back").css("width", width);
	
	var height = $su(document).height();
	$su("#su_frameless_div_back").css("height", height);
	
	/*	Now the light div	*/
	$su("#"+div).appendTo("body");
	$su("#"+div).addClass("su_frameless_div");
	
	$su("#"+div).show();
	
	$su("#"+div).css("top", (($su(document).height()-$su("#"+div).height())/2));
	$su("#"+div).css("left", (($su(window).width()-$su("#"+div).width())/2));
	
	$su(window).keydown(function(event) {
		if(event.keyCode == '27') {
			hideFramelessDiv(div);
		}
	});
}

function hideFramelessDiv(div)
{
	$su("#su_frameless_div_back").hide();
	$su("#"+div).hide();
	return false;
}

function toggle_hidden_fields(el, expression)
{
	var stop_index = $su(el).parents("li:last").nextAll("li:not(.su_hidden_field):first").index(el);
	if(stop_index == -1) stop_index = 9999;
	if(eval(expression))
	{
		if($su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+")").size() > 0)
		{
			$su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+"):hidden").slideDown("normal");
			$su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+"):visible").css("display", "block");
		}
		else
		{
			$su(el).parents("li:last").children(".su_hidden_field:lt("+stop_index+")").css("display", "inline");
		}
	}
	else
	{
		if($su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+")").size() > 0)
		{
			$su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+"):visible").slideUp("normal");
			$su(el).parents("li:last").nextAll(".su_hidden_field:lt("+stop_index+"):hidden").css("display", "none");
		}
		else
		{
			$su(el).parents("li:last").children(".su_hidden_field:lt("+stop_index+")").css("display", "none");
		}
	}
}

/**
* Load Validation Functions
* 
* Loads all kinds of things for validation
* 
* @param object $ The jQuery object
*/
var SU_valid_form = false;
function load_validation_functions($)
{
	/*$("#su_admin_container form input[type=submit]").click(function() {
		var which_submit = this;
		if(SU_valid_form === true) return true;
		
		var action = $("#su_admin_container form").attr("action");
		action += (action.indexOf("?") !== -1) ? "&": "?";
		action += "action=validate&submit=1";
		var parameters = $("#su_admin_container form .validate_field").serializeArray();
		$.getJSON(action, parameters, function(data) {
			//process JSON
			if(data === null)
			{
				SU_valid_form = true;
				$(which_submit).click();
			}
			else
			{
				//we currently 
				//ticket #
				$(which_submit).click();
			}
		});
		return false;
	});*/
	
	/*	blur validation event	*/
	$(".validate_field_live").blur(function() {
		validate_field_live_event(this, $, false);
	}).keyup(function() {
		validate_field_live_event(this, $, true);
	});
	
}

/**
* Validate Field Live Event
* 
* @param object el The element that fired the event
* @param object $ The jQuery object
* @param bool only_clear_errors If this is true the function will only clear errors not set them
*/
function validate_field_live_event(el, $, only_clear_errors)
{
	var name = $(el).attr("name");
	var valid = true;
	var error_type = null;
	var validation_types = SU_validation_array[name];
	$.each(validation_types, function(i, type) {
		if(!validate_field($("#su_admin_container [name='"+name+"']"), type))
		{
			valid = false;
			error_type = type;
			return false;
		}
	});
	if(valid === false)
	{
		if($("#su_admin_container [name='"+name+"']").attr("value") != "" || validation_types.indexOf("required") !== -1)
		{
			if(only_clear_errors !== true) error_field($("#su_admin_container [name='"+name+"']"), error_type);
		}
		else if($("#su_admin_container [name='"+name+"']").attr("value") == "" && validation_types.indexOf("required") === -1)
		{
			remove_error_field($("#su_admin_container [name='"+name+"']"));
		}
	}
	else
	{
		remove_error_field($("#su_admin_container [name='"+name+"']"));
	}
	display_tab_errors($);
}

/**
* Tentatively adds an error to the field given
* 
* @oaram object el jQuery object of the element in question
*/
function error_field(el, error_type)
{
	if(el.parent().filter("li").size() > 0)
	{
		if(!el.parent().filter("li").hasClass("field_error"))
		{
			el.parent().filter("li").addClass("field_error");
			el.parent().filter("li").append('<div class="error_message" style="display:none"><div><img border="0" src="images/icons/famfamfam/mini/action_stop.gif" style="vertical-align: bottom;"/>'+error_langs["_LANG_GLOBAL_ERROR_"+error_type.toUpperCase()]+'</div></div>');
			el.parent().filter("li").find("div.error_message").slideDown();
		}
	}
	else
	{
		if(!el.prev("label[for='"+el.attr("name")+"']").hasClass("field_error"))
		{
			el.prev("label[for='"+el.attr("name")+"']").addClass("field_error");
		}
	}
}

/**
* Removes an error from the field given
* 
* @oaram object el jQuery object of the element in question
*/
function remove_error_field(el)
{
	if(el.parent().filter("li").size() > 0)
	{
		if(el.parent().filter("li").hasClass("field_error"))
		{
			el.parent().filter("li").children("div.error_message").slideUp('normal', function() {
				$su(this).remove();
				el.parent().filter("li").removeClass("field_error");
				display_tab_errors($su);
			});
		}
	}
	else
	{
		if(el.prev("label[for='"+el.attr("name")+"']").hasClass("field_error"))
		{
			el.prev("label[for='"+el.attr("name")+"']").removeClass("field_error");
		}
	}
}

/**
* Validate Fields
* 
* @TODO Enable additional parameters to the validation functions
* 
* @oaram object el jQuery object of the element in question
*/
function validate_field(el, type)
{
	switch (type)
	{
		case "email":
			return validate_email(el.attr("value"));
		break;
		
	}
	return true;
}

/**
* Display Tab Errors
* 
* 
*/
function display_tab_errors($)
{
	var errors = false;
	//remove the class first before we add it back to the ones that need it
	$("ul.ui-tabs-nav li").each(function() {
		if($(this).find("a span").hasClass("field_error"))
		{
			$(this).find("a span img").remove();
			$(this).find("a span").removeClass("field_error");
		}
	});
	
	var valid = true;
	$("#su_admin_container li.field_error").each(function() {
		var id = $(this).parents("div.ui-tabs-panel").attr("id");
		if(!$("ul.ui-tabs-nav li a[href='#"+id+"'] span").hasClass("field_error"))
		{
			$("ul.ui-tabs-nav li a[href='#"+id+"'] span").addClass("field_error").append("<img src='images/icons/famfamfam/mini/action_stop.gif' border='0' style='vertical-align:bottom;padding-left: 4px;' />");
			errors = true;
		}
	});
	
	if(errors)
	{
		$("#su_admin_container .su_button_green").attr("disabled", "disabled");
	}
	else
	{
		$("#su_admin_container .su_button_green").removeAttr("disabled");
	}
}

$su(document).ready(function($) {
	/*	These functions we call on every page. 	*/
	/*	They may not be used but if not there is no error.	*/
	
	/*	Add indexOf to array for IE	*/
	if (!Array.prototype.indexOf)
	{
	  Array.prototype.indexOf = function(elt /*, from*/)
	  {
		var len = this.length >>> 0;
	
		var from = Number(arguments[1]) || 0;
		from = (from < 0)
			 ? Math.ceil(from)
			 : Math.floor(from);
		if (from < 0)
		  from += len;
	
		for (; from < len; from++)
		{
		  if (from in this &&
			  this[from] === elt)
			return from;
		}
		return -1;
	  };
	}

	
	/*	Setup help links action	*/
	$("#su_admin_help_link a").click(function() {
		if($(this).parent().find("ul").size() > 0)
		{
			$(this).parent().find("ul").slideToggle();
			return false;
		}
		else
		{
			$(this).parents("ul").slideToggle();
			return true;
		}
	});
	
	/*	Load tabs	*/
	$("#su_tabs_container").tabs();
	
	/*	Stripe admin tables	*/
	$(".su_admin_table tr:even").addClass("alternate_color");
	$(".su_admin_table li:even").addClass("alternate_color");
	
	/*	Disable Admin Forms submitting on enter key	*/
	$("#su_admin_container form").keypress(function (e) {
		if(e.which == 13) return false;
	});
	
	/*	Add animation to open/close section help links	*/
	$(".su_section_help_link, .su_help_close").click(function() {
		if($(this).parents("fieldset:last").find(".su_section_help").size() > 0)
		{
			$(this).parents("fieldset:last").find(".su_section_help").slideToggle("normal");
		}
		else
		{
			$(this).parents(".ui-tabs-panel:last").find(".su_section_help").slideToggle("normal");
		}
		return false;
	});
	
	/*	Display errors on tab	*/
	display_tab_errors($);
	
	/*	Add classes to prep client-side validation	*/
	if((typeof SU_validation_array) != 'undefined')
	{
		$.each(SU_validation_array, function(field, validation_types) {
			$("#su_admin_container [name='"+field+"']").addClass("validate_field");
			$.each(validation_types, function(i, type) {
				if(SU_standard_validation_types.indexOf(type) !== -1)
				{
					$("#su_admin_container [name='"+field+"']").addClass("validate_field_live");
					return false;
				}
			});
		});
	}
	
	/*	Determine whether to bind submit AJAX valiation	*/
	if($("#su_admin_container form .validate_field").size() > 0)
	{
		load_validation_functions($);
		$("#su_admin_container .validate_field_live").blur();
	}
});//end of $su(document).ready function
