/**
  * Show and Hide an object depending on checkbox status
  * Uses prototype library
  * @var object checkbox   The checkbox object
  * @var string obj_id     The id of the object to show/hide
  */
function checkbox_showhide(checkbox, obj_id)
{
	if(checkbox.checked) {
		$(obj_id).show();
	} else {
		$(obj_id).hide();
	}
}

/**
  * Show and Hide Front Admin Links
  * Uses prototype library
  * @var object button   The containter of the clicked link
  */
function toggle_admin_links(button)
{
	//alert(button.innerHTML);
	if(button.innerHTML == 'SHOW LINKS') {
		$$('.admin_edit_link').each(function(e){e.show();});
		button.innerHTML = 'HIDE LINKS';
		AE_AjaxFrontRequest('main.php', 'admin_switch_display_front_links', {parameters:'display_front_links=1'});
	} else {
		$$('.admin_edit_link').each(function(e){e.hide();});
		button.innerHTML = 'SHOW LINKS';
		AE_AjaxFrontRequest('main.php', 'admin_switch_display_front_links', {parameters:'display_front_links=0'});
	}
}


/**
  * Inserts multiple fields.
  */
function insertValue(textbox, listbox) {
    if(listbox.options.length > 0) {
        var chaineAj = "";
        var NbSelect = 0;
        for(var i=0; i<listbox.options.length; i++) {
            if (listbox.options[i].selected){
                NbSelect++;
                if (NbSelect > 1)
                    chaineAj += ", ";
                chaineAj += listbox.options[i].value;
            }
        }

        //IE support
        if (document.selection) {
            textbox.focus();
            sel = document.selection.createRange();
            sel.text = chaineAj;
            textbox.focus();
        }
        //MOZILLA/NETSCAPE support
        else if (textbox.selectionStart || textbox.selectionStart == "0") {
            var startPos = textbox.selectionStart;
            var endPos = textbox.selectionEnd;
            var chaineSql = textbox.value;

            textbox.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
			textbox.focus();
        } else {
            textbox.value += chaineAj;
			textbox.focus();
        }
    }
}

/**
  * Inserts multiple fields into the end of the text box
  */
function insertValueAtEnd(textbox, listbox) {
    if(listbox.options.length > 0) {
        var chaineAj = "";
        var NbSelect = 0;
        for(var i=0; i<listbox.options.length; i++) {
            if (listbox.options[i].selected){
                NbSelect++;
                if (NbSelect > 1)
                    chaineAj += ", ";
                chaineAj += listbox.options[i].value;
            }
        }

		textbox.value += chaineAj;
		textbox.focus();
    }
}

/**
  * Get the index of a selected radio button in a radio button group
  */
function getSelectedRadioButtonIndex(buttonGroup)
{
 for (var i = 0; i < buttonGroup.length; i++) {
	if (buttonGroup[i].checked) {
	   return i;
	}
 }
 return 0;
}

/**
  * Get the Value of the selected radio button in a radio button group
  */
function getSelectedRadioButtonValue(buttonGroup)
{
	var b = getSelectedRadioButtonIndex(buttonGroup);
	return buttonGroup[b].value;
}

/**
  * Set the select box selected item by it's value
  * @param obj selbox	The select box
  * @param string value	The desired value
  * @return bool True on success, or false on failure
  * @author Lukas Labryszewski [lukasl at ackleymedia dot com]
  */
function setSelectBoxByValue(selbox, value) {
	for (var i=0; i<selbox.length; i++) {
		if (selbox.options[i].value == value) {
			selbox.selectedIndex=i;
			return true;
		}
	}
	return false;
}


/**
 * From: http://www.quirksmode.org/js/dhtmloptions.html
 *	You can use this function to gain access to the HTML element you want to influence.
 *	It will pass you the HTML element you asked for, regardless of browser DOM. 
 *	Of course the element must have a proper ID and, if your script must work in Netscape 4, should have a position defined in the style sheet.
 *	This supports nested layers. 
 * It's called like this:
 *  var x = new getObj('layername');
 * Using the object:
 *  Please note that you cannot do anything with the object x itself, it is merely a container for its two properties:
 *  x.obj, giving access to the actual HTML element. You have to use this property to read out or set anything else than styles. 
 *  x.style, giving access to the styles of the HTML element. You have to use this property to read out or set the styles of the element. 
 */
function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
	this.obj = getObjNN4(document,name);
	this.style = this.obj;
  }
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}


// Goes through the inputString and replaces every occurrence of fromString with toString
function replaceSubstring(inputString, fromString, toString) 
{
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


// Returns true or false based on whether the specified string is found
// in the array. This is based on the PHP function of the same name.
// Written by Beau Lebens <beau@dentedreality.com.au>
function in_array(stringToSearch, arrayToSearch) 
{
	for (s = 0; s < arrayToSearch.length; s++) {
		thisEntry = arrayToSearch[s].toString();
		if (thisEntry == stringToSearch) {
			return true;
		}
	}
	return false;
}

// -------------------------------------------------------------------
// Author: Matt Kruse <matt@mattkruse.com> WWW: http://www.mattkruse.com/
//
// TabNext()
// Function to auto-tab phone field
// Arguments:
//   obj :  The input object (this)
//   event: Either 'up' or 'down' depending on the keypress event
//   len  : Max length of field - tab when input reaches this length
//   next_field: input object to get focus after this one
// -------------------------------------------------------------------
var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				}
			}
		}
	}



// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire;
}


// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}


function popBlankWindow(url,w,h,attrib)
{
//	var specs= "scrollbars=no,width="+w+",height="+h+",resizable=yes";
	var specs= "scrollbars=yes,width="+w+",height="+h + ",resizable=yes";
	if (attrib) {
		specs += ","+attrib;
	}
	newWindow = window.open(url,"pop_console",specs);
	newWindow.focus();
}



function messageWindow(title, msg)
{
  var width="300", height="125";
  var left = (screen.width/2) - width/2;
  var top = (screen.height/2) - height/2;
  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top;
  var msgWindow = window.open("","msgWindow", styleStr);
  var head = '<head><title>'+title+'</title></head>';
  var body = '<center>'+msg+'<br><p><form><input type="button" value="   Done   " onClick="self.close()"></form>';
  msgWindow.document.write(head + body);
}


/**
 * Trims a string
 */
function trim(str)
{
	return str.replace(/^\s*/, "").replace(/\s*$/,"");
}



function preloadImages() {
	var d=document; if(d.images){ if(!d.p) d.p=new Array();
		var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}


/**
 * Add to Favorites function
 * @param string urlAddress The URL to bookmark
 * @param string pageName   The bookmark name
 */
function addToFavorites(urlAddress, pageName) 
{
	if (window.external) {
		window.external.AddFavorite(urlAddress,pageName);
	} else { 
		alert("Sorry! Your browser doesn't support this function.\nUsually clicking Ctrl+D will bookmark the page - but close this dialog box first.");
	}
}

/**
 * Activates active objects on the page (flash, etc) (otherwise warning on the object - click to activate)
 */
function activate_objects()
{
	theObjects = document.getElementsByTagName("object"); 
	for (var i = 0; i < theObjects.length; i++) { 
		// For Media Player it does not work correctly - so we need to activate Media Player manually
		if(theObjects[i].id!='MediaPlayer') {
			theObjects[i].outerHTML = theObjects[i].outerHTML; 
		}
	}
}


/**
* prevent to send form if we press enter in the text field
* Paste that in text field :  onkeydown="javascript:checkEvent()"
* Enter
*/
function checkAKey(event)
{
       if (event.keyCode == 13) {
       	if(event.srcElement){
            if (event.srcElement.type == 'text') 
                   event.returnValue=false;
       	}
	}
}


/** 
 * Get current time 
 * @author Lukas Labryszewski [lukasl at ackleymedia dot com]
 * @version		2005-05-11	Original
 */
function get_current_time(show_seconds, _12hrclock)
{
	var Digital=new Date()
	var hours=Digital.getHours()
	var minutes=Digital.getMinutes()
	var seconds=Digital.getSeconds()
	if (_12hrclock) {
		var dn="AM";
		if (hours>=12){
			dn="PM";
			hours=hours-12;
		}
		if (hours==0)
			hours=12;
	}
	if (minutes<=9)
		minutes="0"+minutes
	if (seconds<=9)
		seconds="0"+seconds

	var str = hours+":"+minutes;
	if (show_seconds) {
		str += ":"+seconds;
	}
	if (_12hrclock) {
		str += " "+dn;
	}
	return str;
}


/**
 * Ajax request to a method for Front Modules.
 * @example  AE_AjaxFrontRequest('delete_images', {confirmMsg:'Are you sure?', updateElementID:'image_container'} );
 * @param string   method     The ajax method to call in the current module, without the 'ajax_' prepend.
 * @param hash     options    Options hash.
 * 							  parameters       - Any additional parameters may be passed here as a "var1=val1&var2=val2" string
 * 							  confirmMsg       - if confirmMsg is set, then this function will first present a confirmation message and only proceed if OK is selected.
 * 							  updateElementID  - if updateElementID is specified, then on success, this method will update this element with the resulting HTML from the AJAX call.
 * 							  onSuccess        - if onSuccess is specified, then on success, this method will call this function with (resp, jsonObj) parameters.
 */
function AE_AjaxFrontRequest(url, method, options )
{
	if (!method) {
		return false;
	}
	
	//{confirmMsg:"", options.updateElementID:"update"}
	
	if(options.confirmMsg) {
		if (!confirm(options.confirmMsg)) {
			return false;
		}
	}
	
	var ajax_parameters = "ajax="+method;
	
	if(options.parameters) {
		ajax_parameters += "&" + options.parameters;
	}
	//alert(url);
	new Ajax.Request(url, { 
		onSuccess : 
			function(resp, jsonObj) {
				//$(options.updateElementID).innerHTML = resp.responseText;
				//alert(resp.responseText);
				
				if (jsonObj.debug) {
					alert(jsonObj.debug);
				}
				if(jsonObj.result != 'OK') {
					alert(jsonObj.result);
					return;
				}
				// if the ajax call specified to update an element then update the element innerHTML container
				if(jsonObj.update_element && options.updateElementID) {
					$(options.updateElementID).innerHTML = resp.responseText;
				}
				
				if(options.onSuccess) {
					var eval_str = options.onSuccess+"(resp, jsonObj)";
					eval(eval_str);
				}
			},
		 onFailure : function(resp) { alert("There's been an error."); },
		 parameters : ajax_parameters } );
	return true;
}
