﻿// global variables

var debugEnable = false;
var d = new Date();

// Archivo JScript
function $(id)
{
    return document.getElementById(id);
}

String.format = function()
{
    if( arguments.length == 0 )
        return null;
        
    var str = arguments[0];

    for(var i=1;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    
    return str;
}

function FormatNumber(num,decimalNum,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
   if (isNaN(parseInt(num))) return "NaN";
    var bolLeadingZero = true;
	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);
	tmpNumStr = tmpNumStr.replace('.', ',');

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(",");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	return tmpNumStr;		// Return our formatted string!
}

function DoPostBack(id, action, index)
{
    var f = document.forms[0];
    var h = document.createElement("INPUT");
    h.type = "hidden";
    h.name = id + '_' + action + '_';
    h.value = index;
    f.appendChild(h);

    document.forms[0].submit();
    
    return true;
}


function MultiArray(iRows,iCols)
{
    var i;
    var j;
    var a = new Array(iRows);
    for (i=0; i < iRows; i++)
    {
        a[i] = new Array(iCols);
        for (j=0; j < iCols; j++)
        {
            a[i][j] = "";
        }
    }
    return(a);
}

function Confirmation(message)
{
    if (!confirm(message == null ? '¿Está Ud. seguro?' : message)) return false;                
    return true;
}

/***** AJAX ****/

function FinishAJAXMethod(res)
{        
    if (res.error != null && res.error.Message != null)
    {
        if (debugEnable && confirm(res.error.Message + '\r\n\r\n¿Desea ver los detalles?'))
        {
            alert(res.json);
        }
        return false;
    }
    return true;
}

function SwitchOrder(ctrl)
{
    document.location = ctrl.value;
}

/*************************
 COOKIE CONTROL
 *************************/
function Set_Cookie( name, value, expires, path, domain, secure ) 
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) 
{
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/***********************************
 end Cookie control
 **********************************/

/*************
    Events
**************/

function HookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.addEventListener)
    element.addEventListener(eventName, callback, false);
  else if(element.attachEvent)
    element.attachEvent("on" + eventName, callback);
}

/*************
    end Events
**************/

function ValidateMoreGroups(groups)
{
    var groupsarray = groups.split(',');
    var result = true;
    
    for (var i=0; i<groupsarray.length; i++)
    {
        if (!Page_ClientValidate(groupsarray[i]));
        {
            result = false;
        }
    }
    
    return result;
}

function CC(ctrl, className)
{
    ctrl.className = className;
}

function CBI(ctrl, imageName)
{
    var image = "url('" + imageName + "')";
    ctrl.style.backgroundImage = image;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function SetLocation(location)
{
    window.location.href = location;
}

// Validation

function GetControl(id, name, index)
{
    return $(id + '_' + name + '_' + index);
}

function GetControlValue(id, name, index)
{
    var ctrl = $(id + '_' + name + '_' + index);
    
    return ctrl.value;
}

function SetControlValue(id, name, index, value)
{
    var ctrl = $(id + '_' + name + '_' + index).value = value;    
}

function GetControlName(id, name, index)
{
    var ctrl = $(id + '_' + name + '_' + index);
    return ctrl.name;
}

function GetControlID(id, name, index)
{
    return id + '_' + name + '_' + index;       
}

function ValidateRequired(ctrl, message)
{
    var ret = ctrl.value != '';
    
    while ((ctrl = ctrl.nextSibling) != null)
    {    
        if (ctrl.id != null && ctrl.id.indexOf('Validator') > 0)    
        {
            ctrl.style.display = (ret ? 'none' : '');
            break;
        }
    }        
    // returns null if true and returns message or empty string if not true
    return ret ? null : (message == null ? '' : message);
}

function ValidateByRegExp(ctrl, message, regexp)
{
	if(!ctrl.value.match(regexp))
	{	    
		return message;
	}
	else
	{
	    return null;
	}
}

function ValidateChecked(ctrl, message)
{       
	return ctrl.checked ? null : (message == null ? '' : message);
}

function ValidateCompare(ctrl1, ctrl2, message)
{
    return ctrl1.value == ctrl2.value ? null : (message == null ? '' : message);
}

function ValidateCurrency(ctrl, message)
{       
	return ValidateByRegExp(ctrl, message, /^\d+([,.](\d{1,2})){0,1}$/);
}

function ValidateAmount(ctrl, message)
{
	return ValidateByRegExp(ctrl, message, /^\d*([,.](\d{1,4})){0,1}$/);
}

function ValidateInteger(ctrl, message)
{
	return ValidateByRegExp(ctrl, message, /^\d*$/);
}

function ValidateDate(ctrl, message)
{
    return ValidateByRegExp(ctrl, message, /^\d\d?\.\d\d?\.\d?\d?\d\d$/);
}

function ValidateDateTime(ctrl, message)
{
    return ValidateByRegExp(ctrl, message, /^\d\d?\.\d\d?\.\d?\d?\d\d ?\d\d:\d\d$/)
}

function RunPageValidates(id, list)
{
    var retVal = true;
    for (var i=0; i<list.length; i++)
    {
        retVal = retVal && RunPageValidate(id, list[i]);
    }    
    return retVal;
}

function RunPageValidate(id, list)
{
    try
    {
        var message = '';
        var result = true;
        var tempmessage;
        
        // Init message 
        SetValidationMessage(id, null)
        
        // Process validators    
        for (var i=1; i<list.length; i++)
        {
            tempmessage = eval(list[i]);
            
            // validator return null if correct otherwise return error message
            if (tempmessage != null)
            {
                if (tempmessage.length > 0)
                {
                    message += tempmessage + '<br />';
                }
                result = false;
            }
        }    
        
        SetValidationMessage(id, message);    
        return result;
    }
    catch (ex)
    {
         SetValidationMessage(id, ex.message);
         return false;
    }
}

function SetValidationMessage(id, message)
{
    var ctrl = $(id + '_ValidationPanel');
    var okPanel = $(id + '_OkPanel');
    
    if (ctrl != null)
    {
        if (message != null && message != '')
        {                                
            ctrl.style.display = '';
            ctrl.innerHTML = message;                                                
        }
        else
        {
            ctrl.style.display = 'none';
        }
        
        if (okPanel != null)
        {
            okPanel.style.display = 'none';
            okPanel.innerHTML = '';
        }
    }
}


// Double click prevention

/* This disables Double clicks on submit buttons */
var currentClick;
var timerSet;

function ClearClick()
{
    currentClick = '';
    timerSet = false;
}

function DC(id)
{
    var retVal = !(id == currentClick);
    currentClick = id;

    if (!timerSet)
    {
        setTimeout('ClearClick()',60000);
        timerSet = true;
    }
    return retVal;
}

/***********************************************************************************
    nStr - The number to be formatted, as a string or number.
    inD - The decimal character for the input, such as '.' for the number 100.2
    outD - The decimal character for the output, such as ',' for the number 100,2
    sep - The separator character for the output, such as ',' for the number 1,000.2
************************************************************************************/
function addSeparatorsNF(nStr, inD, outD, sep)
{
    if (nStr != '0.00')
    {
	    nStr += '';
	    var dpos = nStr.indexOf(inD);
	    var nStrEnd = '';
	    if (dpos != -1)
	    {
		    nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		    nStr = nStr.substring(0, dpos);
	    }
	    var rgx = /(\d+)(\d{3})/;
	    while (rgx.test(nStr)) {
		    nStr = nStr.replace(rgx, '$1' + sep + '$2');
	    }
	    return nStr + nStrEnd;
	}
	return '0';
}

function Uncheck(id, name, index)
{
    if (index == null) index = '';
    GetControl(id, name, index).checked = false;
}

function showLoggedMenu()
{
    $('navigationPrivado').style.display = '';
    $('navigation').style.display = 'none';
    Set_Cookie('isLoggedMenuDisplayed', 'true', '', '/', '', '');
}


function showPrintList(name, id)
{
//    if (fichaId.length > 1)
//    {
//    alert(name);
//        $(fichaId).style.borderColor = "#A9A9A9";
//        setOpacity($(fichaId), 7);
//    }    
    if (name)
    {
        fichaId = name;    
        SetControlValue(id, "Ficha", "", fichaId);
        $(fichaId).style.borderColor = "#A30A36";
        setOpacity($(fichaId), 10)
    }    
}

function setOpacity(element, value) {
	element.style.opacity = value/10;
	element.style.filter = 'alpha(opacity=' + value*10 + ')';
}


function showPrintPDF(id, ficha)
{	
    var url = null;
    
    if (ficha)
    {
        url = 'http://www.guiacoches.com/ImprimirFicha.aspx?Tipo=coches&Id=' + id + '&Ficha=' + ficha;
        window.location.href = url;
    }
    else if (id)
    {
        url = 'http://www.guiacoches.com/ImprimirFicha.aspx?Tipo=coches&Id=' + id + '&Ficha=' + ficha;
        window.location.href = url;
    }
    else
    {
        alert("Error, seleccione la ficha a imprimir");
    }
}

function hideLoggedMenu()
{
    $('navigationPrivado').style.display = 'none';
    $('navigation').style.display = '';
    Set_Cookie('isLoggedMenuDisplayed', 'false', '', '/', '', '');
}


function showScriptMenu() {
            jQuery("#2a").lavaLamp({
                fx: "backout", 
                speed: 700,
                click: function(event, menuItem) {
                    return true;
                }
            });
}

function setMenus()
{
    var isLoggedMenuDisplayed = Get_Cookie('isLoggedMenuDisplayed');
    if (isLoggedMenuDisplayed == null)
    {
        isLoggedMenuDisplayed = 'true';
    }        
    if (isLoggedMenuDisplayed == 'true')
    {
        showLoggedMenu();
        showScriptMenu();
    }
    else
    {
        hideLoggedMenu();
    }
}

function openMapWindow(url)
{
  var date = new Date();
  var winNumber = date.getTime();
  x = (self.screen.width - 635) / 2;
  y = (self.screen.height - 485) / 2; 
  window.open('http://www.guiacoches.com/' + url,'mapWindow' + winNumber.toString(),'top=' + y + ', left=' + x + ', width=635,height=485,resizable=no,menubar=no,toolbar=no,status=no,location=no'); 
}

function doWatermark()
{ 
    var q = document.getElementById('q'); 
    var n = navigator; 
    var l = location; 
    if (n.platform == 'Win32') 
    { 
        var b = function() 
        { 
            if (q.value == '') 
            { 
                q.style.background = '#FFFFFF url(http:\x2F\x2Fwww.google.com\x2Fcoop\x2Fintl\x2Fes\x2Fimages\x2Fgoogle_custom_search_watermark.gif) left no-repeat'; 
            } 
        }; 
        var f = function() 
        { 
            q.style.background = '#ffffff'; 
        }; 
        
        q.onfocus = f; 
        q.onblur = b; 
        if (!/[&?]q=[^&]/.test(l.search)) 
        { 
            b(); 
        }         
    }
}

function getNewSubmitForm(){
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    //submitForm.method = "POST";
    return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue, inputType){
    var newElement = document.createElement("INPUT");    
    newElement.setAttribute('type', inputType);    
    newElement.setAttribute('name', elementName);
    newElement.setAttribute('value', elementValue);
    
    inputForm.appendChild(newElement);    
    return newElement;
}

function createSearchForm(){
    var submitForm = getNewSubmitForm();
    var searchValue = document.getElementById('q');
    
    createNewFormElement(submitForm, "cx", "016492756949472426418:nsiev344uqw", "hidden");
    createNewFormElement(submitForm, "ie", "UTF-8", "hidden");
    createNewFormElement(submitForm, "cof", "FORID:9", "hidden");
    createNewFormElement(submitForm, "q", searchValue.value, "hidden");
    
    submitForm.id= "cse-search-box";
    submitForm.action= "busquedaglobal";
    
    submitForm.submit();
    
    return false;
}
