var enabled_edit_fields_time = new Array();
var enabled_edit_fields_comment = new Array();
var commentsArray = new Array();
var ajaxWindowLink;
var ajaxWindowYPos = 0;
var ajaxWindowXPos = 0;

// ARRAY EXTENSIONS

if (!Array.prototype.push) Array.prototype.push = function() {
    for (var i=0; i<arguments.length; i++) this[this.length] = arguments[i];
    return this.length;
}

Array.prototype.find = function(value, start) {
    start = start || 0;
    for (var i=start; i<this.length; i++)
        if (this[i]==value)
            return i;
    return -1;
}

Array.prototype.has = function(value) {
    return this.find(value)!==-1;
}

// FUNCTIONAL

function map(list, func) {
    var result = [];
    func = func || function(v) {return v};
    for (var i=0; i < list.length; i++) result.push(func(list[i], i, list));
    return result;
}

function filter(list, func) {
    var result = [];
    func = func || function(v) {return v};
    map(list, function(v) { if (func(v)) result.push(v) } );
    return result;
}


// DOM

function getElem(elem) {
    if (document.getElementById) {
        if (typeof elem == "string") {
            elem = document.getElementById(elem);
            if (elem===null) throw 'cannot get element: element does not exist';
        } else if (typeof elem != "object") {
            throw 'cannot get element: invalid datatype';
        }
    } else throw 'cannot get element: unsupported DOM';
    return elem;
}

function hasClass(elem, className) {
    return getElem(elem).className.split(' ').has(className);
}

function getElementsByClass(className, tagName, parentNode) {
    parentNode = !isUndefined(parentNode)? getElem(parentNode) : document;
    if (isUndefined(tagName)) tagName = '*';
    return filter(parentNode.getElementsByTagName(tagName),
        function(elem) { return hasClass(elem, className) });
}


// DOM EVENTS

function listen(event, elem, func) {
    elem = getElem(elem);
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(event,func,false);
    else if (elem.attachEvent)  // IE DOM
        elem.attachEvent('on'+event, function(){ func(new W3CDOM_Event(elem)) } );
        // for IE we use a wrapper function that passes in a simplified faux Event object.
    else throw 'cannot add event listener';
}

function mlisten(event, elem_list, func) {
    map(elem_list, function(elem) { listen(event, elem, func) } );
}

function W3CDOM_Event(currentTarget) {
    this.currentTarget  = currentTarget;
    this.preventDefault = function() { window.event.returnValue = false }
    return this;
}

// MISC CLEANING-AFTER-MICROSOFT STUFF
function isUndefined(v) {
    var undef;
    return v===undef;
}

//<--lib ends

//Our functions starts....

//Open popup. Can be called directly
function Popup(url, target, features)
{
	var theWindow = window.open(url, target, features);
	theWindow.focus();
	return theWindow;
}
//Holder for Popup(). As it's to be registered with event listener
function PopupHolder(e)
{
	Popup(e.currentTarget.getAttribute('href'), e.currentTarget.getAttribute('target') || J_POPUP_TARGET, J_POPUP_FEATURES);
	e.preventDefault();
}
//show balloon. Can be called directly
function ShowBalloon(objA, x, y)
{
	gTmp_ATitle = objA.title; //preserve the title in global var
	objA.title = ''; //empty it, so that it won't popup
	var tmp_title = 'Help', tmp_desc = gTmp_ATitle, pos_colon; //safe init
	//e.g., gTmp_ATitle = 'Help: Help is a help...'
	if ((pos_colon=gTmp_ATitle.indexOf(':')) !=-1 )
		{
			tmp_title = gTmp_ATitle.substring(0, pos_colon);
			tmp_desc = gTmp_ATitle.substring(pos_colon+1);
		}
	var balloon = document.getElementById(J_BALLOON);
	balloon.className = J_CLSBALLOON;
	balloon.style.display = 'inline';
	balloon.style.width = J_BALLOONWIDTH + 'px';
	balloon.style.top = y + 'px';
	balloon.style.left = x + 'px';
	balloon.innerHTML = '<span class="' + J_CLSBALLOONTITTLE + '">'+ tmp_title +'<\/span><div class="' + J_CLSBALLOONDESC + '">'+ tmp_desc + '<\/div>';
	return true;
}

function ShowBalloonHolder(e)
{
	var posx = 0, posy = 0;
	if (e.pageX || e.pageY) //Moz
		{
			posx = e.pageX;
			posy = e.pageY;
		}
	 else if (event.clientX || event.clientY) //IE. Note: event.x not working fine
		{
			if(document.body.scrollTop==0){
				var targetText = e.currentTarget;
				targetText = targetText + "";
				targetText = targetText.substring(targetText.indexOf('#')+1);
				targetText = 'Help_'+targetText;
				targetText = document.getElementById(targetText);
				var posy = getAbsoluteOffsetTopConfirmation(targetText);
				var posx = getAbsoluteOffsetLeftConfirmation(targetText);
				//alert(posx+'--'+posy+J_BALLOONPOSADJX);
			}
			else{
				posx = event.clientX + document.body.scrollLeft;
				posy = event.clientY + document.body.scrollTop;
			}
		}
	//Note: using the x, y as it is cause the div to flicker in certain border points in FF (IE, Opera works find).
	ShowBalloon(e.currentTarget, posx+J_BALLOONPOSADJX, posy+J_BALLOONPOSADJY);
	e.preventDefault();
}
//Hides balloon.
function HideBalloon(objA)
{
	var balloon = document.getElementById(J_BALLOON);
	balloon.style.display = 'none';
	objA.title = gTmp_ATitle; //re-assign
}
//Holder for HideBaloon. As it's to be registered with event listener
function HideBalloonHolder(e)
{
	HideBalloon(e.currentTarget);
	e.preventDefault();
}

//global vars
var gTmp_ATitle; //temp variable to hold and swap title attributes
//global constants. Used to change behaviors quickly
//presumably IE doesn't support const on strings
var J_BALLOON = 'balloon'; //balloon id
var J_CLSHELP = 'clsHelp';
var J_CLSBALLOON = 'clsBalloon';
var J_CLSBALLOONTITTLE = 'clsBalloonTittle';
var J_CLSBALLOONDESC = 'clsBalloonDesc';
var J_BALLOONPOSADJX = 10;
var J_BALLOONPOSADJY = 10;
var J_POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,width=400,height=300,top=200,left=200';
var J_POPUP_TARGET = 'help';
var J_BALLOONWIDTH = 200;
var J_CLSPHOTOLINKCLASS = 'clsPhotoVideoEditLinks';
var J_CLSPHOTOLINKBALLOON = 'clsPhotoBalloon';
var J_CLSPHOTOBALLOONTEXT = 'clsPhotoBalloonText';
var J_PHOTOBALLOONWIDTH = '90';

listen('load',
		window,
		function()
		{
			//create balloon div...
			var balloon = document.createElement('div');
			balloon.id = J_BALLOON;
			document.body.appendChild(balloon);
			//listen...
			mlisten('mouseover', getElementsByClass(J_CLSHELP,'a'), ShowBalloonHolder);
			mlisten('mouseout', getElementsByClass(J_CLSHELP,'a'), HideBalloonHolder);
			mlisten('click', getElementsByClass(J_CLSHELP,'a'), PopupHolder);
			mlisten('mouseover', getElementsByClass(J_CLSPHOTOLINKCLASS,'a'), ShowPhotoLinkBalloonHolder);
			mlisten('mouseout', getElementsByClass(J_CLSPHOTOLINKCLASS,'a'), HideBalloonHolder);
		}
	);

function Popup(url, target, features)
{
	var theWindow = window.open(url, target, features);
	//http://developer.mozilla.org/en/docs/DOM:window.open
	//window.open will return null on popup blocker and sort of
	if (theWindow==null)
			location.href = url;
		else if (window.focus)
			theWindow.focus();
	return theWindow;
}

function selectAll(thisForm)
	{
		for (var i=0; i<thisForm.elements.length; i++)
			{
				if (thisForm.elements[i].type == "checkbox")
					{
						if(thisForm.checkall.checked)
							{
								thisForm.elements[i].checked=true;
							}
							else
								{
									thisForm.elements[i].checked=false;
								}
					}
			}
	}

//function for check box manage
function CheckAll(form_name,check_all,isO,noHL)
	{
		var trk=0;
		var frm = eval('document.'+form_name);
		var check_frm = eval('document.'+form_name+'.'+check_all);

		for (var i=0;i<frm.elements.length;i++)
		{
			var e=frm.elements[i];
			if ((e.name != check_all) && (e.type=='checkbox'))
			{
				if (isO != 1)
				{
					trk++;
					if(e.disabled!=true)
						e.checked=check_frm.checked;
				}
			}
		}
	}

//function for disable the select all checkbox column
function disableHeading(frmname)
{
		var targetForm = document.getElementById(frmname);

		for (var i=1; i<targetForm.elements.length; i++)
			{
				if (targetForm.elements[i].type == "checkbox")
				{	//alert(i);
					if (targetForm.elements[i].checked)
					{	//alert('chekall');
						targetForm.elements[0].checked=true;
					}
					else
					{
						targetForm.elements[0].checked=false;
						break;
					}
				}
			}
}

/**
 *
 * @access public
 * @return void
 **/
function hide_element()
{
    for (var i = 0; i < arguments.length; i++)
	{
      var element = $(arguments[i]);
      if (element)
      	element.style.display = 'none';
    }

}

function show_element()
{
    for (var i = 0; i < arguments.length; i++)
	{
      var element = $(arguments[i]);
      if (element)
      	element.style.display = '';
    }

}
//**************** Regular Expression functions*******************/
function RegularExpressionReplace(expression, subject, replaced)
	{
	  var re = new RegExp(expression, "g");
	  return subject.replace(re, replaced);
	}
function StringReplcae(find_string, replace_string, subject)
	{
		return RegularExpressionReplace(find_string, subject, replace_string);
	}
function replace_string(str, search_str, replace_str)
	{
			var condition = true;
			var inc= 1;
			while(condition)
				{
					str = str.replace(search_str,replace_str);
					if(str.indexOf(search_str)<0)
						condition = false;
					inc++;
				}
			return str;
	}

//**************** confirmation box related functions Start *******************/
//Change position of the confirmation block
//Get multible check box value with comma seperator
var multiCheckValue='';
var minimum_top = 20;
var minimum_left = 20;
var zIndexValue = 200;
// form_name, check_all_name, alert_value, place
var getMultiCheckBoxValue = function(){
	multiCheckValue = '';
	var form_name = arguments[0];
	var check_all_name = arguments[1];
	var alert_value = arguments[2];

	var frm = eval('document.'+form_name);
	var ids = '';
	for(var i=0;i<frm.elements.length;i++){
		var e=frm.elements[i];
		if ((e.name != check_all_name) && (e.type=='checkbox') && e.checked)
			ids += e.value+',';
	}
	if(ids){
		multiCheckValue =ids.substring(0,ids.length-1);
		return true;
	}
	alert_manual(alert_value);
	return false;

}
function showHideScreen(divElm){
	var fromObj = $(divElm);
	fromObj.style.zIndex = zIndexValue;
	fromObj.style.display = 'block';
	if(obj = $('hideScreen')){
		var ss = getPageSizeWithScroll();
		obj.style.width=ss[0]+"px";
		obj.style.height=ss[1]+"px";
		obj.style.display='block';
		return false;
	}
}
function makeQueryAsFormFieldValues(form_name)
	{
		var query = '';
		var frm = eval('document.'+form_name);
		for(var i=0;i<frm.elements.length;i++){
				var e=frm.elements[i];
				if (e.type!='button' && e.type!='checkbox'){
						query += e.name+'='+e.value+'&';
					}
			}
		query =query.substring(0,query.length-1);
		return query;
	}

//**************** confirmation box related functions End *******************/

var getCheckBoxValue = function(){
	var form_name = arguments[0];
	var check_all_name = arguments[1];
	var frm = eval('document.'+form_name);
	var ids = '';
	for(var i=0;i<frm.elements.length;i++){
		var e=frm.elements[i];
		if ((e.name != check_all_name) && (e.type=='checkbox') && e.checked)
			ids += e.value+', ';
	}
	if(ids){
		multiCheckValue =ids.substring(0,ids.length-1);
		return true;
	}
	return false;
}

/************ edit comments end ********/

//For sorting
function changeOrderbyElements(form_name,field_name){
	 	var obj = eval("document."+form_name+".orderby_field");
	 	obj.value = field_name;
	 	obj = eval("document."+form_name+".orderby");
	 	if(obj.value=="asc")
	 		obj.value="desc";
	 	else
	 		obj.value="asc";
	 	eval("document."+form_name+".submit()");
	 	return false;
	}

//for postmethod to paging
function pagingSubmit(formname, start){
	var obj = eval("document."+formname);
	obj.start.value = start;
	obj.submit();
	return false;
}

function CheckAll(form_name,check_all,isO,noHL)
	{
		var trk=0;
		var frm = eval('document.'+form_name);
		var check_frm = eval('document.'+form_name+'.'+check_all);

		for (var i=0;i<frm.elements.length;i++)
		{
			var e=frm.elements[i];
			if ((e.name != check_all) && (e.type=='checkbox'))
			{
				if (isO != 1)
				{
					trk++;
					if(e.disabled!=true)
						e.checked=check_frm.checked;
				}
			}
		}
	}

function toggleElement(myDiv){
	var divObj = $(myDiv);
	if (divObj.style.display=='none')
		divObj.show();
	else
		divObj.hide();
}

function showAvatars(url, pars, divname){
	if ($('loadingAvatars1'))
		$('loadingAvatars1').innerHTML = processingSrc;
	if ($('loadingAvatars2'))
		$('loadingAvatars2').innerHTML = processingSrc;
	ajaxUpdateDiv(url, pars, divname);
}

var originalImageSrc = '';
function selectAvatar(avatarUrl){
	if (originalImageSrc == '')
		originalImageSrc = $('selUserImage').innerHTML;
	if (avatarUrl==0){
		$('selUserImage').innerHTML = originalImageSrc;
		document.form_edit_settings.avatar.value = '';
	}else{
		var posF = avatarUrl.indexOf('avatars/') + 8;
		avatarName = avatarUrl.substring(posF);

		$('selUserImage').innerHTML = '<p id="selImageBorder"><img src="'+avatarUrl+'" /></p>';
		document.form_edit_settings.avatar.value = avatarName;
	}
	document.form_edit_settings.photo.value = '';
}
function changeSheets(url, activeTitle, inactiveTitle, activeSheet){
  if(document.styleSheets){
    var c = document.styleSheets.length;
    for(var i=0;i<c;i++){
      if(document.styleSheets[i].title==inactiveTitle){
        document.styleSheets[i].disabled=true;
      }
	  if(document.styleSheets[i].title==activeTitle){
        document.styleSheets[i].disabled=false;

        Ajax.Responders.unregister(myGlobalHandlers);
		var pars = 'style='+activeSheet;
        var myAjax = new Ajax.Request(
									url,
									{
									method: 'get',
									parameters: pars
									});
      }
    }
  }
}
function changePopupDivPosition(popupDivId){
	var imgObjName = 'img'+popupDivId;
	var imgObj = $(imgObjName);
	var popupObj = $(popupDivId);
	var left = getAbsoluteOffsetLeftConfirmation(imgObj)-parseInt(popupPosition);
	popupObj.style.left = left + 'px';
}

function ffMacOsCloseWindow(){
	var brwsEng=getBrowser();
    var oprSys=getOS();
	//myLightWindow.deactivate();
	hideAllBlocks();
}


function updateorder(url, pars){

	var myAjax = new Ajax.Request(
								url,
								{
								method: 'get',
								parameters: pars
								});
								return false;
}

function getPageSizeWithScroll2(){

	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	//return arrayPageSizeWithScroll;
	return arrayPageSizeWithScroll;
}

function needLiveValidation(field_name, jsCheck){

     if(featured_livevalidation == '')
	       return false;

	var checkLists = jsCheck;
	var lv_field_name = new LiveValidation( field_name );


	for(i=0;i<checkLists.length;i++)
		{
			live_check = checkLists[i].split("|");
			switch(live_check[0])
					{

						case 'Presence':
											lv_field_name.add( Validate.Presence );
											break;
						case 'Email':
											lv_field_name.add( Validate.Email );
											break;

						case 'Emailgroup':
											lv_field_name.add( Validate.Emailgroup );
											break;

						case 'Confirmation':
											lv_field_name.add( Validate.Confirmation, { match: live_check[1] } );
											break;

						case 'Length':
											lv_field_name.add( Validate.Length, { minimum: live_check[1], maximum: live_check[2] } );
											break;

						case 'Acceptance':
											lv_field_name.add( Validate.Acceptance );
											break;

						case 'Numericality':
											lv_field_name.add( Validate.Numericality );
											break;
					}

		}

	/*
	var f18 = new LiveValidation('f18');
	f18.add( Validate.Acceptance );
	var useremail = new LiveValidation( 'useremail' );
	useremail.add( Validate.Presence );
	useremail.add( Validate.Email );
	var message = new LiveValidation( 'message' );
	message.add( Validate.Presence );*/
}


//function to disable submit button and to show processing image
var processingRequest = function(){
	var btnSubmitObj = arguments[0];
	var btnResetObj = arguments[1];
	var selProcessingRequestID = arguments[2];
	$(btnSubmitObj).style.display = 'none';
	$(btnResetObj).style.display = 'none';
	$(selProcessingRequestID).innerHTML = processingSrc + ' ' + LANG_sending_email;
}


function hideSuccessDiv(){
	if($('selMsgSuccess')){
		hideAnimateBlock('selMsgSuccess');
	}
}

var billingFormUpdate=function(){
	var plan_id = arguments[0];
	var url =  arguments[1];
	var pars = 'payCheck=1&plan_id='+plan_id;
	var myAjax = new Ajax.Request(
							url,{method: 'get',
							parameters: pars,
							onComplete: updateBillingForm}
							);
			}

function updateBillingForm(originalRequest){
	data = originalRequest.responseText;
	if(data == 'true')
		{
			if(payment_option != 'standard')
				$('billInfo').style.display = '';
		}
	else
		{
			if(payment_option != 'standard')
				$('billInfo').style.display = 'none';
		}
}

document.onkeydown = checkKeycode;
function checkKeycode(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	if(keycode == 27){
		hideAllBlocks();
	}
}
var showHideDiv = function(){
	var divId = arguments[0];
	var divObj = $(divId);
	var filterObj = '';
	if(arguments.length >= 2)
		filterObj = $(arguments[1]);
	if (divObj.style.display == 'none') {
		divObj.style.display = '';
		if (filterObj)
			filterObj.className = 'clsLinkHover';
	} else {
		divObj.style.display = 'none';
		if (filterObj)
			filterObj.className = 'clsLink';
	}
}

function chkAccecpted(objTerms){
	$('selTerms').innerHTML = '';
	if (!objTerms.checked){
		$('selTerms').innerHTML = 'Required!';
	}
}
function openAjaxWindow(linkid){
	ajaxWindowLink = linkid;
	linkobj = document.getElementById(linkid);
	url = linkobj.href;
	pars = '';
	var myAjax = new Ajax.Request(
								url,
								{
								method: 'get',
								parameters: pars,
								onComplete: ajaxResultOpenAjaxWindow
								});
								return false;
}

function ajaxResultOpenAjaxWindow(originalRequest){
	data = originalRequest.responseText;
	Confirmation('selAjaxWindow', 'frmAjaxWindow', Array('selAjaxWindowInnerDiv'), Array(data), Array('innerHTML'));
	if ((catObj = $('category')) || (sub_catObj = $('sub_category'))){
		br=getBrowser();
		if (br[0] == 'msie' && getMajorVersion(br[1]) == '6'){
			if (catObj = $('category'))
				catObj.style.display = 'none';

			if (sub_catObj = $('sub_category'))
				sub_catObj.style.display = 'none';
		}
	}
	data.evalScripts();
}

function setNingImageStatus(url, pars)
	{
		var myAjax = new Ajax.Request(
								url,
								{
								method: 'get',
								parameters: pars
								});

	}
