//VerticalTabsContent.js
/**
 * @author pmartinez
 */ 
function loadCriticalOffers()
{
	if( document.getElementById('Ofertas_Criticas') == null ) return;
	var oCriticalOffers = oDynamicContent["OfertasCriticas"];
	var offersText="";
	var innerHTML="";
	
	for (var i = 0; i < 4/*oCriticalOffers.Ofertas.length*/; i++) {
		var oElement = oCriticalOffers.Ofertas[i];	
		offersText += "<a class=\"critOfferlnk\" href=\"job/" + 
		oElement[2] + 
		"-\" >" + 
		oElement[1] + /* CHK: efv. Generar el nombre del link con regex */ 
		"</a>" +
		"<br/><span class=\"critOfferEnt\">" + 
		oElement[0] + 
		"</span>&nbsp;<span class=\"critOfferloc\">(" + oElement[3] + ")</span><br/><span class=\"critOfferDt\">"+oElement[4] + "</span><br/>";
	}
	
	innerHTML=document.getElementById('Ofertas_Criticas').innerHTML;
	document.getElementById('Ofertas_Criticas').innerHTML = offersText + innerHTML;
}

//TotalJobOffers.js 
/**
 * @author pmartinez
 */
function GetTotalJobOffers()
{
	document.getElementById('numero_ofertas').innerHTML = addCommas(oDynamicContent["JobsInfo"].TotalSiteJobs);
}


//TagCloud.js
/**
 * @author pmartinez
 */
function GenerateTagCloud(){
	if( document.getElementById('tagcloud') == null )
		return;

	var Cloud = "";
	oJobsInfo = oDynamicContent["JobsInfo"];
	
	for (var i = 0; i < oJobsInfo.CloudElements.length; i++) {
		var oElement = oJobsInfo.CloudElements[i];		
		Cloud += "<a id=\"" + oElement[0] + "\" onmouseover=\"this.className='" + oElement[2] + "_over';\" onmouseout=\"this.className='" + oElement[2] + "';\" class=\"" + oElement[2] + "\" href=\"search.asp?q=&tm=60d&cy=mx&st=" + oElement[0] + "\" TITLE=\"" + addCommas(oElement[3]) + " Ofertas\">" + oElement[1] + "</a> &nbsp;&nbsp;";
	}	
	document.getElementById('tagcloud').innerHTML = Cloud;
	//changeClass("bsq_estado");
}

/*
function GenerateCategoriesCloud(){
	if( document.getElementById('tagcloud') == null )
		return;

	var Cloud = "";
	oJobsInfo = oDynamicContent["CategoriesInfo"];
	
	for (var i = 0; i < oJobsInfo.CloudElements.length; i++) {
		var oElement = oJobsInfo.CloudElements[i];	
		Cloud += "<a id=\"" + oElement[0] + "\" onmouseover=\"this.className='" + oElement[2] + "_over';\" onmouseout=\"this.className='" + oElement[2] + "';\" class=\"" + oElement[2] + "\" href=\"search.asp?tm=60d&fn=F" + oElement[0] + "\" TITLE=\"" + addCommas(oElement[3]) + " Ofertas\">" + oElement[1] + "</a> &nbsp;&nbsp;";
	}	
	document.getElementById('tagcloud').innerHTML =Cloud;
	//changeClass("bsq_categoria");
}
*/

function GenerateCompanyCloud(){
	//console.log("..run...");
	var busc_comp = '<div id="busqueda_compania"><div id="campo_busqueda"><label>Buscar Compa&ntilde;ia<input type="text" name="txt_compania" id="txt_compania" size="30" /><input type="button" name="btn_enviar_comp" id="btn_enviar_comp" value="Buscar" onclick="requestLikeCompany();"/></label></div><div id="abcdario">	<div style="clear: both;"></div></div><div id="compania" class="loading"><div id="cargando"><img src="img/loading.gif" /><br />  Cargando...</div></div><div style="clear:both;"></div>	</div>';
	document.getElementById('tagcloud1').innerHTML = busc_comp;
	//changeClass("bsq_comp");
	
	var bc = new BC();
	bc.populateAbcedario();	
}

//TabContent.js
function ddtabcontent(tabinterfaceid){
	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container
	this.enabletabpersistence=true
	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array
	this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values)
	this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
}

ddtabcontent.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

ddtabcontent.setCookie=function(name, value){
	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
}

ddtabcontent.prototype={

	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers
		this.cancelautorun() //stop auto cycling of tabs (if running)
		var tabref=""
		try{
			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=this.tabs[tabid_or_position]
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tabref!="") //if a valid tab is found based on function parameter
			this.expandtab(tabref) //expand this tab
	},

	cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )
		if (dir=="next"){
			var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0
		}
		else if (dir=="prev"){
			var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1
		}
		if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function
			this.cancelautorun() //stop auto cycling of tabs (if running)
		this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])
	},

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
		this.selectedClassTarget=objstr || "link"
	},

	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to
		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref
	},

	urlparamselect:function(tabinterfaceid){
		var result=window.location.search.match(new RegExp(tabinterfaceid+"=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL
		return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
	},

	expandtab:function(tabref){
		var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand
		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		this.expandsubcontent(subcontentid)
		this.expandrevcontent(associatedrevids)
		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"
			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "selected" : ""
		}
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)
		this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array
	},

	expandsubcontent:function(subcontentid){
		for (var i=0; i<this.subcontentids.length; i++){
			var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)
			subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value
		}
	},

	expandrevcontent:function(associatedrevids){
		var allrevids=this.revcontentids
		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface
			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"
		}
	},

	setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array)
		for (var i=0; i<this.hottabspositions.length; i++){
			if (tabposition==this.hottabspositions[i]){
				this.currentTabIndex=i
				break
			}
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		this.cycleit('next', true)
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var selectedtab=-1 //Currently selected tab index (-1 meaning none)
		var selectedtabfromurl=this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index
		this.automodeperiod=automodeperiod || 0
		for (var i=0; i<this.tabs.length; i++){
			this.tabs[i].tabposition=i //remember position of tab relative to its peers
			if (this.tabs[i].getAttribute("rel")){
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)
				this.tabs[i].onclick=function(){
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
				}
				if (selectedtabfromurl==i || this.enabletabpersistence && selectedtab==-1 && parseInt(persistedtab)==i || !this.enabletabpersistence && selectedtab==-1 && this.getselectedClassTarget(this.tabs[i]).className=="selected"){
					selectedtab=i //Selected tab index, if found
				}
			}
		} //END for loop
		if (selectedtab!=-1) //if a valid default selected tab index is found
			this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class)
		else //if no valid default selected index found
			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	} //END int() function

} //END Prototype assignment

//ContentHelper.js
/**
* @author pmartinez
* creation_date:"03/06/2008 04:53:31 p.m."
*/
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function changeClass(obj){
	var c = document.getElementById(obj);
	var nodes = document.getElementById("bus_tabs").getElementsByTagName("li");
	for(var i=0;i<nodes.length;i++){
		nodes[i].className = "";
	}
	c.className ="current";
}

function getEl(elementId)
{
	return document.getElementById(elementId);
}

function $a() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

//efv: Ejecucion

//loadCriticalOffers();
//loadCritical();

//Silverlight Test FALLBACK
function isPlugin(){
	//console.log("INICIANDO FALLBACK");
	var isSilverlightInstalled = false;
	
	/* La ultima version estable de silverlight apartir del 19/11/08 es 2.0.31005.0 para IE
	* utilizamos la comprobacion de la version 2.0.31005.0 pero en FF3 usamos solamente la 2.0 ya que
	* la version 2.0.31005.0 tiene un bug y no funciona bien.
	*/
    try
    {
        //check on IE
        try
        {
            var slControl = new ActiveXObject('AgControl.AgControl');
			if(slControl.isVersionSupported('2.0.31005.0')){
				isSilverlightInstalled = true;
			}else {
				isSilverlightInstalled = false;
			}
			
			//alert("isSilverlightInstalled:" + isSilverlightInstalled);
        }
        catch (e)
        {
            //either not installed or not IE. Check Firefox
			
            if (navigator.plugins["Silverlight Plug-In"] )
            {
				//console.log(navigator.plugins["Silverlight Plug-In"].description);
				//console.log(navigator.userAgent);
				//alert(navigator.plugins["Silverlight Plug-In"].description);
				if(navigator.userAgent.indexOf("Firefox/3") == -1){
					isSilverlightInstalled = false;
					//console.log("No es firefox " + navigator.userAgent.indexOf("Firefox/3"));
				}
				else if(navigator.plugins["Silverlight Plug-In"].description == "3.0.40818.0" || navigator.plugins["Silverlight Plug-In"].description == "2.0.31005.0"){
					//alert(navigator.plugins["Silverlight Plug-In"].description)
					isSilverlightInstalled = true;
					//console.log("La version es superior a la 3");
				}
				else if(navigator.plugins["Silverlight Plug-In"].description == "2.0"){
					isSilverlightInstalled = false;
					//console.log("La version es inferior a la 2");
				}
            }
        }
    }
    catch (e)
    {
		alert(e);
    }
	//console.log("isSilverlightInstalled: " + isSilverlightInstalled);
    return isSilverlightInstalled;
}

function slTest (){
		if(!isPlugin()){
			var doc = document.getElementById("silverlightControlHost");
			doc.innerHTML = document.getElementById("sl_fallback").innerHTML;
		}
}

GenerateTagCloud();
GetTotalJobOffers();


