/**
 * Hook all input elements in forms
 */
window.onload = function()
{
	var forms = document.getElementsByTagName('form');

	for (var i=0; i<forms.length; i++)
	{
		var inputs = forms[i].getElementsByTagName('input');

		for (var j=0; j<inputs.length; j++)
		{
			addInputSubmitEvent(forms[i], inputs[j]);
		}
	}
};

/**
 * Add submit event for every input in forms when Enter is pressed
 */
function addInputSubmitEvent(form, input)
{
	input.onkeydown = function(e)
	{
		e = e || window.event;

		if (e.keyCode == 13)
		{
			form.submit(); return false;
		}
	};
}

/* Nodrošina sadaļu pārslēgšanu pirmajā lapā (zem logo) */
function changeFrontpageIntro(current_id, all_ids)
{
	s = all_ids.split(',');

	for (i=0; i<s.length; i++)
	{
		var el1 = document.getElementById('frontpageintro_'+s[i]);
		var el2 = document.getElementById(s[i]);

		if (s[i] == current_id)
		{
			el2.className = 'active';
			el1.style.display = 'block';
			if (el1.firstChild.banner) {
				el1.firstChild.banner.start();
			}
		}
		else
		{
			el2.className = '';
			el1.style.display = 'none';
			if (el1.firstChild.banner) {
				el1.firstChild.banner.stop();
			}
		}
	}
}

function changeFrontpageIntro2(current_id, all_ids)
{

	s = all_ids.split(',');

	for (i=0; i<s.length; i++)
	{
		var el1 = document.getElementById('frontpageintro2_'+s[i]);
		var el2 = document.getElementById('intro_link2_'+s[i]);

		if (s[i] == current_id)
		{
			el2.className = 'active';
			el1.style.display = 'block';
		}
		else
		{
			el2.className = '';
			el1.style.display = 'none';
		}

	}
}

/* Ievieto padotos datus elementā ar id = dst_id */
function insertContents(data, dst_id)
{
	e = document.getElementById(dst_id);
	e.innerHTML = data;
}

/* shows or hides element with elid id */
function sh(elid, visible)
{
	var el = document.getElementById(elid);

	if (!el) { return; }

	el.style.visibility = (visible ? 'visible' : 'hidden');
}

function confirmAction()
{
	return confirm('Vai tiešām vēlaties veikt šo darbību?')
}


/**
* Opens content in a popup window
*/
function printwnd(url)
{
	window.open(url, 'printview', 'width=720,height=550,status=0,toolbar=1,resizable=0,scrollbars=1,location=1,menubar=1,directories=1');
}

function smsKeyPress(textArea, maxLength)
{
	if (textArea.value.length > maxLength)
	{
		textArea.value = textArea.value.substring(0, maxLength);
	}

	var countArea = document.getElementById('SMSCount');

	var count = maxLength - textArea.value.length;

	countArea.innerHTML = count;
}


function submitAjax(url, divId, formID)
{
	sh("loading", true);
	new Ajax.Updater(divId, url, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formID), requestHeaders:['X-Update', divId]})
}


/**
 * Class used to automatically or manually switch between banners (in one category)
 * The class uses script.aculo.us class for the effects and also requires prototype.js
 * @author Edmunds Kalnins
 * @company mendo www.mendo.lv
 */
var banners = {
	timer: null, // used to delay activation/deactivation
	activeBannerNr: null, // nr of the currently active banner+button
	interval: null, // interval ID that is used to automatically advance banners
	butId: null,
	banId: null,
	containerId: null,

	/**
	 * Load this class into a container object parentId. This way we can keep track of all class variables.
	 * @param butId - id of the button to activate (minus the last character, which should be number)
	 * @param banId - id of the banner to activate (minus the last character, which should be number)
	 * @param containerId - id of element containing banners
	 */
	load: function(butId,banId,containerId) {
		this.butId = butId;
		this.banId = banId;
		this.containerId = containerId;
		if($(containerId).style.display == "block") {
			this.start();
		}
	},

	/**
	 * Initializes banners - select randomly one of the available and also turns it on
	 * and turns on interval switching
	 * @param butId - id of the button to activate (minus the last character, which should be number)
	 * @param banId - id of the banner to activate (minus the last character, which should be number)
	 */
	start: function() {
		if (this.interval) {
			this.stop();
		}

		butId = this.butId;
		banId = this.banId;

		// first find number of banners
		nr = 1;
		while(document.getElementById(banId+""+nr)) {
			nr++;
		}

		// *** Only for Piedavajumi banners, need to start with 1st

		//randomNr = Math.floor(Math.random() * (nr-1))+1;
		randomNr = 1;

		//alert(banId);
		nextBan = document.getElementById(banId+""+randomNr);
		nextBut = document.getElementById(butId+""+randomNr);

		if(nextBan != null && nextBut != null) {
			// check if there is an active banner and deactivate it
			this.findActiveNr(this.banId);
			if(this.activeBannerNr) {
				this.deactivate($(this.butId+this.activeBannerNr),$(this.banId+this.activeBannerNr));
			}

			active_ban = this.banId+this.activeBannerNr;

			this.activate(nextBut,nextBan);

			if(active_ban == 'ban_piedavajumi_null'){
				/*this.interval = window.setInterval("", 1000*8);
				window.clearInterval(this.interval);*/
				this.interval = window.setTimeout("$('"+this.containerId+"')"+".banner.advance('"+butId+"','"+banId+"'); window.setInterval(\"$('"+this.containerId+"').banner.advance('"+butId+"','"+banId+"');\", 1000*4);", 1000*8);
				//this.interval = window.setInterval("$('"+this.containerId+"')"+".banner.advance('"+butId+"','"+banId+"')", 1000*4);

			}
			else{
				this.interval = window.setInterval("$('"+this.containerId+"')"+".banner.advance('"+butId+"','"+banId+"')", 1000*4);
			}

		}
		else {
			// alert("Nesanāca aktivizēt. Mēģināju aktivizēt: \n" + banId+""+randomNr + " un " + butId+""+randomNr);
		}

	},

	/**
	 * Stops automatic banner advancement
	 */
	stop: function() {
		window.clearInterval(this.interval);
	},

	/**
	 * Switches on banner nr, while deactivating the currently active one
	 * @param activateNr - number of the banner and button to activate
	 * @param butId - id of the button to activate (minus the last character, which should be number)
	 * @param banId - id of the banner to activate (minus the last character, which should be number)
	 */
	switchOn: function(nr, butId, banId) {
		this.findActiveNr(banId);
		this.stop();

		thisBan = document.getElementById(banId+""+this.activeBannerNr);
		thisBut = document.getElementById(butId+""+this.activeBannerNr);

		nextBan = document.getElementById(banId+""+nr);
		nextBut = document.getElementById(butId+""+nr);

		if(nextBan != null && nextBut != null) {
			this.deactivate(thisBut,thisBan);
			this.activate(nextBut,nextBan);
		}
		else {

		}
	},

	/**
	 * activate an element
	 * @param butElement - element reference of the button to activate
	 * @param banElement - element reference of the banner to activate
	 */
	activate: function(butElement,banElement) {
		//alert(banElement.id);
		if (banElement.id == "ban_piedavajumi_1"){
			this.timer = setTimeout("Effect.Appear('"+banElement.id+"',{duration: 0.3})", 300); //201
		}
		else{
			this.timer = setTimeout("Effect.Appear('"+banElement.id+"',{duration: 0.3})", 100); //201
		}
		// Effect.Appear(banElement.id);
		butElement.className = "active";
	},

	/**
	 * deactivate an element
	 * @param butElement - element reference of the button to activate
	 * @param banElement - element reference of the banner to activate
	 */
	deactivate: function(butElement,banElement) {
		id = banElement.id;
		// this.timer = setTimeout("Effect.Fade('"+id+"',{duration: 0.1})", 150);
		// banElement.style.display = "none";
		Effect.Fade(banElement.id,{duration: 0.1});
		butElement.className = "";
	},

	/**
	 * Advance to the next banner
	 *
	 * The function checks if the banner activeBannerNr+1 exists and activates it
	 * or activates banner Nr1 if it doesnt exist
	 * @param butId - id of the button to activate (minus the last character, which should be number)
	 * @param banId - id of the banner to activate (minus the last character, which should be number)
	 */
	advance: function(butId,banId) {

		this.findActiveNr(banId);

		if(this.activeBannerNr != null) {
			nextNr = this.activeBannerNr*1 + 1;
			if (document.getElementById(banId+""+nextNr) == null) {
				nextNr = 1;
			}
		}
		else {
			nextNr = 1;
		}

		thisBan = document.getElementById(banId+""+this.activeBannerNr);
		thisBut = document.getElementById(butId+""+this.activeBannerNr);

		nextBan = document.getElementById(banId+""+nextNr);
		nextBut = document.getElementById(butId+""+nextNr);

		if(nextBan != null && nextNr != null) {
			this.deactivate(thisBut,thisBan);
			this.activate(nextBut,nextBan);
		}
		else {

		}
	},

	/**
	 * Finds active Nr for the banners with id banId# and setis it to activeBannerNr.
	 * @param banId - id of the banner (minus the last character, which should be number)
	 */
	findActiveNr: function(banId) {
		nr = 1;
		while(nextban = document.getElementById(banId+""+nr)) {
			if(nextban.style.display != "none") {
				this.activeBannerNr = nr;
			}
			nr++;
		}

	}
}



/**
 * Adds new field for application form
 *
 */

function addField() {

  // global counters
	if(!document["FileFieldNum"]) {
      document["FileFieldNum"] = 1;
      }
	else {
		document["FileFieldNum"] ++;
  }

	var newPropertyNum = document["FileFieldNum"];

	var divOriginalId = "fields";

	newDiv = $(divOriginalId).cloneNode(true);
	newDiv.id = divOriginalId + newPropertyNum;


	// update field names from [name][xx] to [name][xx][nr] and clear values
	$(newDiv).immediateDescendants().each(function(child) {
		if(child.name) {

	var start = child.name.lastIndexOf('_');
	var end = child.name.lastIndexOf(']');
	//var number = child.name.substring(start+1,end)*1 + 1;
	child.name = child.name.substring(0,start) + '_' + (newPropertyNum + 1) + ']';


		//	child.name = child.name.substr(0,child.name.length-1)+"_]["+newPropertyNum+"]";
			child.id = child.id + "_" + newPropertyNum;
		}
		if(child.value) {
			child.value = "";
		}
	});

	if(newPropertyNum > 1) {
      prevIdNum = newPropertyNum-1;
      lastDivId = $(divOriginalId).id+prevIdNum;
      $(lastDivId).parentNode.insertBefore(newDiv,$(lastDivId).nextSibling);
	}
	else {
		$(divOriginalId).parentNode.insertBefore(newDiv,$(divOriginalId).nextSibling);
	}

  //"dzēst" linkam
	$(newDiv).getElementsBySelector('div.del').invoke('update',"<label class='pos'><a href='#' onclick=rem("+newPropertyNum+");>Dzēst</a></label>");
	$(newDiv).getElementsBySelector('div.fortype').invoke('update','<select name="data[Ffield][type__]['+newPropertyNum+']"  onchange="chck('+newPropertyNum+')" id="FfieldType"><optionvalue="1" >input</option><option value="2" >textarea</option><option value="3" >checkbox</option><option value="4" >dropdown</option></select> ');



}




cnt=1;
/**
 * Adds another position to Fleet/Rent-a-Position application
 *
 * @param int type - type of the position. p - passenger c - comercial (field names depend on this)
 */
function addPosition(count, show) {
	//noņem display none



	/* if no type type is p */
	type = "";

	if(show)
	{
	$("fields_"+type).setStyle({display:"block"});
	$("fields_a"+type).setStyle({display:"none"});
  if(type=="") cnt=1;


	}
	else {

	//if(count) alert("nav 3");
  /* global counters */
	if(!document["fields"+type+"FieldNum"]) {
      document["fields"+type+"FieldNum"] = 2;
      cnt++;
      }
	else {
		document["fields"+type+"FieldNum"] ++;
		cnt++;
  }

	var newPropertyNum = document["fields"+type+"FieldNum"];

	if(count){
	var divOriginalId = "fieldsContainer_"+type;
	} else var divOriginalId = "fieldsContainer_"+type;


	newDiv = $(divOriginalId).cloneNode(true);
	newDiv.id = divOriginalId + newPropertyNum;
	$(newDiv).setStyle({display:"block"});

	/* update field names from [name][xx] to [name][xx_][nr] and clear values */
	$(newDiv).immediateDescendants().each(function(child) {
		if(child.name) {
			child.name = child.name.substr(0,child.name.length-1) + "_]["+newPropertyNum+"  ]";
			child.id = child.id + "_" + newPropertyNum;
		}
		if(child.value) {
			child.value = "";
		}
	/*
		if(child.onchange){
		alert("buu _ "+newPropertyNum);
			//child.onchange = "'calc(" + newPropertyNum +")'";
			Event.observe(child.id + "_" + newPropertyNum, 'change', calc(newPropertyNum));
		}
		*/
	});

	/* update number

	if(count) $(newDiv).getElementsBySelector('div.nr').invoke('update',newPropertyNum+count-2);
	else $(newDiv).getElementsBySelector('div.nr').invoke('update',newPropertyNum);
	*/
	//"dzēst" linkam
	$(newDiv).getElementsBySelector('div.del').invoke('update',"<label class='pos'><a href='#' onclick=rem("+newPropertyNum+");>Dzēst</a></label>");
	//else $(newDiv).getElementsBySelector('div.del').invoke('update',"<a href='#' onclick=rem("+newPropertyNum+");>Dzēst</a>");
	$(newDiv).getElementsBySelector('div.fortype').invoke('update','<select name="data[Ffield][type__]['+newPropertyNum+'  ]"  onchange="chck('+newPropertyNum+')" id="FfieldType_'+newPropertyNum+'"><option value="1" >input</option><option value="2" >textarea</option><option value="3" >checkbox</option><option value="4" >dropdown</option></select> ');

	if(newPropertyNum > 2) {
      prevIdNum = newPropertyNum-1;
      lastDivId = $(divOriginalId).id+prevIdNum;
      $(lastDivId).parentNode.insertBefore(newDiv,$(lastDivId).nextSibling);
	}
	else {
		$(divOriginalId).parentNode.insertBefore(newDiv,$(divOriginalId).nextSibling);
	}
	}

	if(newPropertyNum) chck(newPropertyNum);
}




function checkform (form)
{
  var s=document.getElementsByName("data[Autoform][title_lv]");
  for(var i=0;i<s.length;i++)
  {
    s[i].value = s[i].value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    if(s[i].value == "")
    {
      alert("Pieteikuma nosaukums LV nedrīkst būt tukšs!");
      return false;
    }
    else return true;
  }
}


function setFocus()
{
  document.getElementById('UserUsername').focus()
}

/**
 *
 *
 */
function showDialogPage(ids, activeID)
{
	s = ids.split(',');

	for (i=0; i<s.length; i++)
	{
		el = document.getElementById("a-"+s[i]);
		el.className ="";
		$(s[i]).hide();
	}

	$(activeID).show();
	el = document.getElementById("a-"+activeID);
	el.className ="active";
}



function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];
					if(oRegExp.test(oElement.getAttribute("class")))
					{
	            arrReturnElements.push(oElement);
	        }
	    }
	    return (arrReturnElements);
}
