/**
 * jQuery hashchange 1.0.0
 * 
 * (based on jquery.history)
 *
 * Copyright (c) 2008 Chris Leishman (chrisleishman.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
(function($) {

$.fn.extend({
    hashchange: function(callback) { this.bind('hashchange', callback) },
    openOnClick: function(href) {
		if (href === undefined || href.length == 0)
			href = '#';
		return this.click(function(ev) {
			if (href && href.charAt(0) == '#') {
				// execute load in separate call stack
				window.setTimeout(function() { $.locationHash(href) }, 0);
			} else {
				window.location(href);
			}
			ev.stopPropagation();
			return false;
		});
    }
});

// IE 8 introduces the hashchange event natively - so nothing more to do
if ($.browser.msie && document.documentMode && document.documentMode >= 8) {
	$.extend({
		locationHash: function(hash) {
	        if (!hash) hash = '#';
	        else if (hash.charAt(0) != '#') hash = '#' + hash;
	        location.hash = hash;
	    }
	});
	return;
}

var curHash;
// hidden iframe for IE (earlier than 8)
var iframe;

$.extend({
	locationHash: function(hash) {
		if (curHash === undefined) return;

		if (!hash) hash = '#';
		else if (hash.charAt(0) != '#') hash = '#' + hash;
		
		location.hash = hash;
		
		if (curHash == hash) return;
		curHash = hash;
		
		if ($.browser.msie) updateIEFrame(hash);
		$.event.trigger('hashchange');
	}
});

$(document).ready(function() {
    curHash = location.hash;
    if ($.browser.msie) {
        // stop the callback firing twice during init if no hash present
        if (curHash == '') curHash = '#';
        // add hidden iframe for IE
        iframe = $('<iframe />').hide().get(0);
        $('body').prepend(iframe);
        updateIEFrame(location.hash);
        setInterval(checkHashIE, 100);
    } else {
        setInterval(checkHash, 100);
    }
});
$(window).unload(function() { iframe = null });

function checkHash() {
    var hash = location.hash;
    if (hash != curHash) {
        curHash = hash;
        $.event.trigger('hashchange');
    }
}

if ($.browser.msie) {
    // Attach a live handler for any anchor links
    $('a[href^=#]').live('click', function() {
        var hash = $(this).attr('href');
        // Don't intercept the click if there is an existing anchor on the page
        // that matches this hash
        if ($(hash).length == 0 && $('a[name='+hash.slice(1)+']').length == 0) {
            $.locationHash(hash);
            return false;
        }
    });
}

function checkHashIE() {
    // On IE, check for location.hash of iframe
    var idoc = iframe.contentDocument || iframe.contentWindow.document;
    var hash = idoc.location.hash;
    if (hash == '') hash = '#';

    if (hash != curHash) {
        if (location.hash != hash) location.hash = hash;
        curHash = hash;
        $.event.trigger('hashchange');
    }
}

function updateIEFrame(hash) {
    if (hash == '#') hash = '';
    var idoc = iframe.contentWindow.document;
    idoc.open();
    idoc.close();
    if (idoc.location.hash != hash) idoc.location.hash = hash;
}

})(jQuery);


function quickselect(selectvalue) {
$('#ToolID').val(selectvalue);
settool(document.forms["orderform"].elements["ToolID"].value);
}

function jsCheckIMEI(IMEI, Checksum) // Must be a string
{
	var i, Sum, Tmp;
	var rExp = new RegExp("^[0-9]{15}$", "");
	if (! rExp.test(IMEI)) return false;
	if (! Checksum) return true;
	for (i=0, Sum=0;  i<14; i++)
	{
		Tmp = (IMEI.charAt(i) * ((i%2) + 1));
		Sum += ((Tmp % 10) + parseInt(Tmp / 10));
	}
	return (((10 - (Sum % 10)) % 10) == IMEI.charAt(14));
}

function jsCheckEmail(Email) // Must be a string
{
	var i, r;
	var x = Email.split("@");
	if (x.length != 2) return false;
	r = new RegExp("^[0-9a-zA-Z_\\-\\.]+$", "");
	if (! r.test(x[0])) return false;
	var y = x[1].split(".");
	if (y.length < 2) return false;
	for (i=0; i<y.length; i++)
	{
		r = new RegExp("^[0-9a-zA-Z\\-]{2,}$", "");
		if (! r.test(y[i])) return false;
		if (y[i].charAt(0)=='-' || y[i].charAt(y[i].length-1)=='-') return false;
	}
	return true;
}


function goto() { 
var nmarca = $('#sMarcas').val();
var nmodelo = $('#sModelos').val();
if (nmarca !=0 && nmodelo !=0) {
location="/liberar-"+nmarca+"-"+nmodelo+".html";
}}

function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
// alert("Your browser does not support AJAX.");
return null;
}
} 

function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "ddcontent6aa9.html?brand=" + document.getElementById('brand').value, true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}

function doWork2(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "ddcontent6aa9.html?brand=" + document.getElementById('brand2').value, true);
httpObject.onreadystatechange = setOutput2;
httpObject.send(null);
}
}


function doWork3(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "meiframe/ddcontent.php/index6aa9.html?brand=" + document.getElementById('brand2').value, true);
httpObject.onreadystatechange = setOutput2;
httpObject.send(null);
}
}

function doWork4(){
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "ddcontent14c6.html?country=" + document.getElementById('country').value, true);
httpObject.onreadystatechange = setOutput4;
httpObject.send(null);
}
}

function setOutput(){
if(httpObject.readyState == 4){
var combo = document.getElementById('model');
combo.options.length = 0;
var response = httpObject.responseText;
var items = response.split(";");
var count = items.length;
for (var i=0;i<count;i++){
var options = items[i].split("|");
combo.options[i] =
new Option(options[0],options[1]);
}
}
}

function setOutput2(){
if(httpObject.readyState == 4){
var combo = document.getElementById('model2');
combo.options.length = 0;
var response = httpObject.responseText;
var items = response.split(";");
var count = items.length;
for (var i=0;i<count;i++){
var options = items[i].split("|");
combo.options[i] =
new Option(options[0],options[1]);
}
}
}

function setOutput4(){
if(httpObject.readyState == 4){
var combo = document.getElementById('NetworkID');
combo.options.length = 0;
var response = httpObject.responseText;
var items = response.split(";");
var count = items.length;
for (var i=0;i<count;i++){
var options = items[i].split("|");
combo.options[i] =
new Option(options[0],options[1]);
}
}
}



/* from messages.js */


// form validation function //
function validate(form) {
  var name = form.name.value;
  var email = form.email.value;
  var gender = form.gender.value;
  var message = form.message.value;
  var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
  var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
  var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
  if(name == "") {
    inlineMsg('name','You must enter your name.',2);
    return false;
  }
  if(!name.match(nameRegex)) {
    inlineMsg('name','You have entered an invalid name.',2);
    return false;
  }
  if(email == "") {
    inlineMsg('email','<strong>Error</strong><br />You must enter your email.',2);
    return false;
  }
  if(!email.match(emailRegex)) {
    inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
    return false;
  }
  if(gender == "") {
    inlineMsg('gender','<strong>Error</strong><br />You must select your gender.',2);
    return false;
  }
  if(message == "") {
    inlineMsg('message','You must enter a message.');
    return false;
  }
  if(message.match(messageRegex)) {
    inlineMsg('message','You have entered an invalid message.');
    return false;
  }
  return true;
}


// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "/images/msg_arrow.gif"; 
}


function selectMarca(){;

$('.select02').load('select2.php', {'marca': ''+$('#sMarcas').val()+''});
}

function getPrecio(idop){
$('#operadores').animate({"width": "0px"}, "slow" , function(){

$('.promo').fadeIn('fast');
})
$('.promo').load('liberar.php', {'marca': ''+$('#idmarca').val()+'','operadora': ''+idop+'','modelo': ''+$('#idmodelo').val()+''});
$('#temp').load('tiempo.php', {'marca': ''+$('#idmarca').val()+'','operadora': ''+idop+'','modelo': ''+$('#idmodelo').val()+''}, function(){
$('#temp').fadeIn('fast');
});
$('#text').load('formulario.php', {'marca': ''+$('#idmarca').val()+'','operadora': ''+idop+'','modelo': ''+$('#idmodelo').val()+''});



}

function comprobar() {
	if (document.forms['formulario'].elements['imei'].value=="") {
		alert('Debes Introducir un Numero IMEI.');
		return false;
	}else if (!( jsCheckIMEI(document.forms['formulario'].elements['imei'].value, true) )) {
		alert('Debes introducir un número de IMEI válido.');
		return false;
	} else if (document.forms['formulario'].elements['nombre'].value=="") {
		alert('Debes Introducir un Nombre');
		return false;
	} else if(document.forms['formulario'].elements['mail'].value!=(document.forms['formulario'].elements['mail'].value).match(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ig)) {
		alert('Debes introducir un E-Mail Valido.');
		return false;
	} else {
		if($('#imei_otros').val() == "") {
			alert('Rellene el campo Provider o S/N.');
			return false;
		} else {
			return true;
		}
	}
}

function jsCheckIMEI(IMEI, Checksum) // Must be a string
{
	IMEI = IMEI.substring(0,15);
	var i, Sum, Tmp;
	var rExp = new RegExp("^[0-9]{15}$", "");
	if (! rExp.test(IMEI)) return false;
	if (! Checksum) return true;
	for (i=0, Sum=0;  i<14; i++)
	{
		Tmp = (IMEI.charAt(i) * ((i%2) + 1));
		Sum += ((Tmp % 10) + parseInt(Tmp / 10));
	}
	return (((10 - (Sum % 10)) % 10) == IMEI.charAt(14));
}
