var google_maps = {"755040256":[2,"Santa Cruz de Tenerife",754974720],"16777216":[1,"\u00c1lava",16777216],"33554432":[1,"Albacete",33554432],"50331648":[1,"Alicante",50331648],"67108864":[1,"Almer\u00eda",67108864],"100663296":[1,"\u00c1vila",100663296],"117440512":[1,"Badajoz",117440512],"419430400":[1,"Islas Baleares",419430400],"134217728":[1,"Barcelona",134217728],"150994944":[1,"Burgos",150994944],"167772160":[1,"C\u00e1ceres",167772160],"184549376":[1,"C\u00e1diz",184549376],"218103808":[1,"Castell\u00f3n",218103808],"251658240":[1,"Ciudad Real",251658240],"268435456":[1,"C\u00f3rdoba",268435456],"452984832":[1,"A Coru\u00f1a",452984832],"285212672":[1,"Cuenca",285212672],"301989888":[1,"Girona",301989888],"335544320":[1,"Granada",335544320],"352321536":[1,"Guadalajara",352321536],"369098752":[1,"Guip\u00fazcoa",369098752],"385875968":[1,"Huelva",385875968],"402653184":[1,"Huesca",402653184],"436207616":[1,"Ja\u00e9n",436207616],"486539264":[1,"Le\u00f3n",486539264],"503316480":[1,"Lleida",503316480],"469762048":[1,"La Rioja",469762048],"520093696":[1,"Lugo",520093696],"536870912":[1,"Madrid",536870912],"553648128":[1,"M\u00e1laga",553648128],"587202560":[1,"Murcia",587202560],"603979776":[1,"Navarra",603979776],"620756992":[1,"Ourense",620756992],"83886080":[1,"Asturias",83886080],"637534208":[1,"Palencia",637534208],"318767104":[1,"Las Palmas",318767104],"654311424":[1,"Pontevedra",654311424],"671088640":[1,"Salamanca",671088640],"754974720":[1,"Tenerife",754974720],"201326592":[1,"Cantabria",201326592],"687865856":[1,"Segovia",687865856],"704643072":[1,"Sevilla",704643072],"721420288":[1,"Soria",721420288],"738197504":[1,"Tarragona",738197504],"771751936":[1,"Teruel",771751936],"788529152":[1,"Toledo",788529152],"805306368":[1,"Valencia",805306368],"822083584":[1,"Valladolid",822083584],"838860800":[1,"Vizcaya",838860800],"855638016":[1,"Zamora",855638016],"872415232":[1,"Zaragoza",872415232],"234881024":[1,"Ceuta",234881024],"570425344":[1,"Melilla",570425344]};var zipcode = {"00":"755040256","01":"16777216","02":"33554432","03":"50331648","04":"67108864","05":"100663296","06":"117440512","07":"419430400","08":"134217728","09":"150994944","10":"167772160","11":"184549376","12":"218103808","13":"251658240","14":"268435456","15":"452984832","16":"285212672","17":"301989888","18":"335544320","19":"352321536","20":"369098752","21":"385875968","22":"402653184","23":"436207616","24":"486539264","25":"503316480","26":"469762048","27":"520093696","28":"536870912","29":"553648128","30":"587202560","31":"603979776","32":"620756992","33":"83886080","34":"637534208","35":"318767104","36":"654311424","37":"671088640","38":"754974720","39":"201326592","40":"687865856","41":"704643072","42":"721420288","43":"738197504","44":"771751936","45":"788529152","46":"805306368","47":"822083584","48":"838860800","49":"855638016","50":"872415232","51":"234881024","52":"570425344"};DHTML_modalMessage=function(){var a;var g;var d;var l;var f;var c;var b;var m;var j;var k;var i;var e;var n;var h;this.url="";this.htmlOfModalMessage="";this.layoutCss="syi.css";this.height=400;this.width=100;this.cssClassOfMessageBox=false;this.shadowDivVisible=true;this.shadowOffset=4;this.MSIE=false;if(navigator.userAgent.indexOf("MSIE")>=0){this.MSIE=true}};DHTML_modalMessage.prototype={setSource:function(a){this.url=a},setHtmlContent:function(a){this.htmlOfModalMessage=a},setSize:function(b,a){if(b){this.width=b}if(a){this.height=a}},setCssClassMessageBox:function(a){this.cssClassOfMessageBox=a;if(this.divs_content){if(this.cssClassOfMessageBox){this.divs_content.className=this.cssClassOfMessageBox}else{this.divs_content.className="modalDialog_contentDiv"}}},setShadowOffset:function(a){this.shadowOffset=a},display:function(){if(!this.divs_transparentDiv){this.__createDivs()}this.divs_transparentDiv.style.display="block";this.divs_content.style.display="block";this.divs_shadow.style.display="block";if(this.MSIE){this.iframe.style.display="block"}this.__resizeDivs();window.refToThisModalBoxObj=this;setTimeout("window.refToThisModalBoxObj.__resizeDivs()",150);this.__insertContent()},setShadowDivVisible:function(a){this.shadowDivVisible=a},close:function(){this.divs_transparentDiv.style.display="none";this.divs_content.style.display="none";this.divs_shadow.style.display="none";if(this.MSIE){this.iframe.style.display="none"}},addEvent:function(b,a,c,d){if(!d){d=""}if(b.attachEvent){b["e"+a+c+d]=c;b[a+c+d]=function(){b["e"+a+c+d](window.event)};b.attachEvent("on"+a,b[a+c+d])}else{b.addEventListener(a,c,false)}},__createDivs:function(){this.divs_transparentDiv=document.createElement("DIV");this.divs_transparentDiv.style.left="0px";this.divs_transparentDiv.style.top="0px";this.divs_transparentDiv.style.position="absolute";this.divs_transparentDiv.style.opacity=0.6;this.divs_transparentDiv.style.filter="alpha(opacity=60)";this.divs_transparentDiv.style.backgroundColor="#000";this.divs_transparentDiv.style.zIndex=1;$(this.divs_transparentDiv).observe("click",function(a){closeMessage()});document.body.appendChild(this.divs_transparentDiv);this.divs_content=document.createElement("DIV");this.divs_content.className="modalDialog_contentDiv";this.divs_content.id="DHTMLSuite_modalBox_contentDiv";this.divs_content.style.zIndex=100000;if(this.MSIE){this.iframe=document.createElement('<IFRAME src="about:blank" frameborder=0>');this.iframe.style.zIndex=90000;this.iframe.style.position="absolute";document.body.appendChild(this.iframe)}document.body.appendChild(this.divs_content);this.divs_shadow=document.createElement("DIV");this.divs_shadow.className="modalDialog_contentDiv_shadow";this.divs_shadow.style.zIndex=95000;document.body.appendChild(this.divs_shadow);window.refToModMessage=this;this.addEvent(window,"scroll",function(a){window.refToModMessage.__repositionTransparentDiv()});this.addEvent(window,"resize",function(a){window.refToModMessage.__repositionTransparentDiv()})},__getBrowserSize:function(){var a,b;if(self.innerHeight){a=self.innerWidth;b=self.innerHeight}else{if(document.documentElement&&document.documentElement.clientHeight){a=document.documentElement.clientWidth;b=document.documentElement.clientHeight}else{if(document.body){a=document.body.clientWidth;b=document.body.clientHeight}}}return[a,b]},__resizeDivs:function(){var e=Math.max(document.body.scrollTop,document.documentElement.scrollTop);if(this.cssClassOfMessageBox){this.divs_content.className=this.cssClassOfMessageBox}else{this.divs_content.className="modalDialog_contentDiv"}if(!this.divs_transparentDiv){return}var d=Math.max(document.body.scrollTop,document.documentElement.scrollTop);var c=Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);window.scrollTo(c,d);setTimeout("window.scrollTo("+c+","+d+");",10);this.__repositionTransparentDiv();var f=this.__getBrowserSize();var b=f[0];var h=f[1];this.divs_content.style.width=this.width+"px";this.divs_content.style.height=this.height+"px";var a=this.divs_content.offsetWidth;var g=this.divs_content.offsetHeight;this.divs_content.style.left=Math.ceil((b-a)/2)+"px";this.divs_content.style.top=(Math.ceil((h-g)/2)+e)+"px";if(this.MSIE){this.iframe.style.left=this.divs_content.style.left;this.iframe.style.top=this.divs_content.style.top;this.iframe.style.width=this.divs_content.style.width;this.iframe.style.height=this.divs_content.style.height}this.divs_shadow.style.left=(this.divs_content.style.left.replace("px","")/1+this.shadowOffset)+"px";this.divs_shadow.style.top=(this.divs_content.style.top.replace("px","")/1+this.shadowOffset)+"px";this.divs_shadow.style.height=g+"px";this.divs_shadow.style.width=a+"px";if(!this.shadowDivVisible){this.divs_shadow.style.display="none"}},__repositionTransparentDiv:function(){this.divs_transparentDiv.style.top=Math.max(document.body.scrollTop,document.documentElement.scrollTop)+"px";this.divs_transparentDiv.style.left=Math.max(document.body.scrollLeft,document.documentElement.scrollLeft)+"px";var b=this.__getBrowserSize();var a=b[0];var c=b[1];this.divs_transparentDiv.style.width=a+"px";this.divs_transparentDiv.style.height=c+"px"},__insertContent:function(){if(this.url){ajax_loadContent("DHTMLSuite_modalBox_contentDiv",this.url)}else{this.divs_content.innerHTML=this.htmlOfModalMessage}}};messageObj=new DHTML_modalMessage();messageObj.setShadowOffset(3);function displayMessage(a){messageObj.setSource(a);messageObj.setCssClassMessageBox(false);messageObj.setSize(400,200);messageObj.setShadowDivVisible(true);messageObj.display()}function processEmbed(c){var b=document.getElementsByTagName("embed");for(var a=0;a<b.length;a++){try{b[a].style.visibility=c}catch(d){}}}function displayStaticMessage(e,c,b,d,a){if(!b){b=400}if(!d){d=120}messageObj.setSize(b,d);messageObj.setHtmlContent(e);messageObj.setCssClassMessageBox(c);messageObj.setSource(false);messageObj.setShadowDivVisible(true);processEmbed("hidden");messageObj.display()}function closeMessage(){processEmbed("visible");messageObj.close()};var cmb_level_1 = 'regione';
var max_images = 9;
var min_accuracy = 5;
var data = "";
var syi_data = "";
var zoom_gm = 12;

var num_uploaded_pics = 0;
var num_pending_uploads = 0;
function request_combo_data (cmb, cat, key, level, selected) {
	if (!parseInt(key)) {
		window.open(key, "_self");
	}
 	var combo = $(cmb);
	if(key == "") {
		combo.selectedIndex = 0;
		combo.length = 1;
		combo.disabled = true;
		if($('div-' + combo.id)) {
			$('div-' + combo.id).style.display="none";
		}
		return;
	} else {
		combo.disabled = false;
	}
    var value;
	if(level > 1) {
		var top1 = $(cmb_level_1);
		value = top1[top1.selectedIndex].value;
	}
    else value = '';
	var _parameters = {_opid:1, c:cat, k:key, l:level, tc:value} ;
	var opt = {
		method:'POST',
		asynchronous:false,
		parameters:_parameters,
		onComplete:function(t) {
			load_combo(t, cmb, cat, selected);
		}
	};
	new Ajax.Request('/new/_syi_actions.php', opt);
}

function swapTip (cat, defCat) {
	$$('.tip_cat').each (function(e) {
        if(e.id != "tip_" + cat)
            e.hide();
        else e.show();
    });

    if(cat == '' && $(defCat))
        $(defCat).show();
}

function onChangeAdjust (pid, src, valor) {
	switch (pid) {
		case 1:
            src = $(src);
            if(src.id != 'h_type')
                break;

            valor = src.value;
            if(valor == __h_type_housing){
					$("syi_category_2").show();
					$("div-h_rooms").show();
					$("div-h_isnew").show();
					$("div-h_m2").show();
            }
            else if(valor == __h_type_office){
					$("syi_category_2").show();
					$("div-h_rooms").hide();
					$("div-h_isnew").hide();
					$("div-h_m2").show();
            }
            else if(valor == __h_type_store){
					$("syi_category_2").show();
					$("div-h_rooms").hide();
					$("div-h_isnew").hide();
					$("div-h_m2").show();
            }
            else if(valor == __h_type_parking){
					$("div-h_rooms").hide();
					$("div-h_isnew").hide();
					$("div-h_m2").hide();
					$("syi_category_2").hide();
            }
            else if(valor == __h_type_land){
					$("syi_category_2").show();
					$("div-h_rooms").hide();
					$("div-h_isnew").hide();
					$("div-h_m2").show();
            }
            else {
                //Unknown type
                break;
            }

            loadHouseSubcategories(valor);
			break;

		case 2:
			[$("div-v_make"),$("div-v_fuel"),$("div-v_year"),$("div-v_km"),$("div-v_cc")].invoke("show");
			if (src == "v_type" && valor == 1) {
				$("div-v_cc").hide();
			}
			if (src == "v_type" && valor == 2) {
				[$("div-v_fuel")].invoke("hide");
			}
			if (src == "v_type" && valor == 3) {
				[$("div-v_make"), $("div-v_fuel"), $("div-v_km"), $("div-v_cc")].invoke("hide");
			}
			loadCarMakers();
			break;

		case 4:
			break;

		default: break;
	}
}

function loadHouseSubcategories(value){
    request_combo_data('subcategory', 10, value, 1, __external_subcategory_selected);
}

function loadCarMakers() {
	var obj = null;
	if ($("v_type").value == 1 /* cars */) {
		obj = __cars;
	}
	if ($("v_type").value == 2 /* motorbike */) {
		obj = __motorbikes;
	}

	var option;
    var targetObj = $("v_make");
    targetObj.options.length = 0;
	for (var i=0; obj && i<obj.length; i++) {
        if(obj[i] == null)
            break;
        targetObj.options[i] = new Option(obj[i].value, obj[i].id);
	}
}

function load_combo (t, cmb, cat, selected) {
	var combo = $(cmb);
	if(t.responseJSON) {
		var datos = t.responseJSON;
		if(datos == "" || datos == "undefined") {
			combo.length = 0;
			combo.disabled = true;
			if($('div-' + combo.id)) {
				$('div-' + combo.id).style.display="none";
			}
			return false;
		} else {
			if($('div-' + combo.id)) {
				$('div-' + combo.id).style.display="";
			}
		}
		var index = 1;
		combo.length = 1;

		for(obj in datos) {
			combo.options[index] = new Option (datos[obj], obj, true, false);
			if(selected != 'undefined') {
				if(selected == obj)
					combo.selectedIndex = index;
			}
			index++;
		}
		return true;
	}
	if($('div-' + combo.id)) {
		$('div-' + combo.id).style.display="none";
	}
	return false;
}

function onLoadSYI (platform_id, data_init, mode) {
	syi_mode = mode;
	switch (platform_id) {
		case 1:
            if(data_init['h_type']){
                cat = $('h_type');
			    cat.value = data_init['h_type'];
			    cat.onchange();
            }
			break;
		case 2:
            if(data_init['v_type']){
                cat = $('v_type');
                cat.value = data_init['v_type'];
                if (cat.value != 3) { // Si no se trata de la opción "otros vehículos".
                    $('div-v_make').show();
                } else $('div-v_make').hide();
                cat.onchange();
            }

			try{
				if(data_init['v_make'] != null){
					var selectedMaker = data_init['v_make'];
					var makers = $('v_make').options;
					for(var i = 0; i < makers.length; i++){
						if(makers[i].value == selectedMaker){
							makers[i].selected = true;
							break;
						}
					}
				}
			}
			catch(err){}
			break;
		case 4:
            if(data_init['g_category']){
                cat = $('g_category');
			    cat.value = data_init['g_category'];
                cat.onchange();
            }
			break;
	}

	if(data_init != "" && syi_mode != 'edit') {
		data = data_init;
		// Province by ZipCode.
		if(data_init.zipcode != "")	{
			setProvByZip($('zipcode'));			
			// If latlong is set, map will show the exact point.	
			if(data_init.latlong != '') {
				// Setting map center point
				var loc = data_init.latlong.substr(1, data_init.latlong.length-2).split(',');
  			    map.setCenter(new GLatLng(loc[0],loc[1]), 13);				
			
				// Must check if address is only zipcode.
				if(data_init['st_name'] != '' && data_init['st_name'] != undefined) {
					var addr_sub = data_init['st_name'].substring(0, 5);
					if(addr_sub == data_init['zipcode']) {
						validateAddressInMap ("center_circle");
					} else {
						validateAddressInMap ("center_marker", loc);
					}
				} else {
					validateAddressInMap ("center_circle");
				}
			} else {			
				validateAddressInMap();
			}
		}
	} 

	if(data_init['images']) {
		setImagesMode();
		for (i=0; i<data_init['images'].length; i++)
			addImage('uploadform', data_init['images'][i]);
	}
	countImages('img_counter');
}

function setOpId (op, f, target) {
	var frm = $(f);
	frm.target = target;
	frm["_opid"].value = op;
}

function setImagesMode() {
	if(num_uploaded_pics >= max_images) {
		$('image_help_text').hide();
		$('image_form' ).hide();
	}
}

function onChangeFileBrowse(d) {
	t = new ImageUpload();
	t.upload();
	clearFileInput(d)
}

function clearFileInput( id ) {
    var elem = $(id);
    elem.parentNode.innerHTML = elem.parentNode.innerHTML;
}

function displayPopMessage (msg, cl, w, h) {
	if(cl == "undefined" || cl == "") {
		cl = "modalDialog_tip";
	}
	msg += "<p><a href=\'#\' onclick=\'closeMessage();return false\'>Cerrar</a>";
	displayStaticMessage(msg, cl, w, h);
}

function submitPost(frm, mode) {
	if(ImageUpload.areImagesUploading() > 0) {
		displayPopMessage('<h3>Subiendo im&aacute;genes...</h3><p>Algunas de las im&aacute;genes seleccionadas a&uacute;n no ha sido cargada completamente. Por favor espere a que el indicador de carga desaparezca y vuelva a pulsar el bot&oacute;n <strong>"Previsualizar anuncio"</strong>.</p>','modalDialog_tip', 400, 150);
		return;
	}

	setOpId(3, 'uploadform', 'hiddenframe');
	f = $(frm);
	f.target = "_self";
	f.submit();
	return false;
}

function publishPost(frm, mode) {
	setOpId(3, 'uploadform', 'hiddenframe');
	var f = $(frm);
	f.target = "_self";
	f['_mode'].value = 'publish';
	f['src_mode'].value = mode;
	f.submit();
	return false;
}

function modifyPreview (frm, mode) {
	f = $(frm);
	f['_mode'].value = mode;
	f['src_mode'].value = 'preview';
	setOpId(3, frm, 'hiddenframe');
	f.target="_self";
	f.submit();
	return false;
}

function imageUploadError(imgid, msg) {
	var img = document.uploads[imgid];
	img.cancel();
	if(msg != "")
		msg = '<h3>' + img.path + '</h3><p>' + msg + '</p>';
    else msg = '<h3>ERROR</h3><p>Ha ocurrido un error durante la carga de la imagen.</p>';
    displayPopMessage(msg, 'modalDialog_tip', 400, 150);
	return false;
}

function addImage (frm, hash) {
	var f = $(frm);
	var d = document.createElement('input');
	d.setAttribute("type", "hidden");
	d.setAttribute("value", hash);
	d.setAttribute("name", "images[]");
	d.setAttribute("id", "hidden-" + hash);
	f.appendChild(d);
	num_uploaded_pics += 1;
	if(num_uploaded_pics >= max_images ) {
		$('image_help_text').hide();
		$('image_form' ).hide();
		return false;
	}
}

function deleteImage (frm, hash) {
	var f = $(frm);
	el = $( "hidden-" + hash );
	el.remove();
	el = $( "image-" + hash );
	el.remove();
	if (selected == hash){
		selected = -1;
	}
	num_uploaded_pics -= 1;
	countImages('img_counter');
	if(num_uploaded_pics < max_images) {
		$('image_help_text').show();
		$('image_form' ).show();
		return false;
	}
}

var selected = -1;

function changeSelected(hash) {
	var other_childs = new Array();
	$("desc-" + hash).innerHTML = "Foto principal";
	$("image_container").childElements().each(function(a) {
		if (a.id.substring(6) != hash) {
			other_childs.push(a.remove());
		}
	});
	var i=0;
	other_childs.each(function(a) {
		$("image_container").appendChild(a);
		$("desc-" + a.id.substring(6)).innerHTML = "Foto #" + (++i);
	})

	$$(".uploaded_image_selected").each(function(e) {
		e.removeClassName("uploaded_image_selected");
		e.addClassName("uploaded_image");
	});
	$(hash).addClassName("uploaded_image_selected");
	$(hash).removeClassName("uploaded_image");
	$("img_selected").value = hash;
	selected = hash;
}

/**************** IMAGE UPLOADING ********************/
document.uploads = new Array();

var ImageUpload = Class.create();
ImageUpload.prototype = {
	loading: false,
	timer: 0,
	id: 0,
	iframe: null,
	hash: '',
	path: '',
	url: '',
	bkp_action:'',
	initialize: function () {
		this.id = document.uploads.length;
		document.uploads[document.uploads.length] = this;
	},
	isLoading:function() {
		return this.loading;
	},
	upload: function() {
		$$('.loading').invoke('show');

		this.loading = true;
		this.timer = setTimeout(this.timeout.bind(this), 300000);
		this.frame = document.createElement('div');
		this.frame.innerHTML += "<iframe id='uploadif_" + this.id + "' name='uploadif_" + this.id +"' style='display:none' ></iframe>";

		$('uploaders').appendChild(this.frame);
		$('uploadform').target = 'uploadif_' + this.id;
		this.bkp_action = $('uploadform').action;
		$('uploadform').action += '?imgid=' + this.id;
		this.path = $('uploadform').fileField.value;
		setOpId(2, 'uploadform', 'uploadif_' + this.id);
		$('uploadform').submit();
		$('uploadform').action = this.bkp_action;
	},
	timeout: function() {
		this.loading = false;
		this.timer = 0;
		this.cleanUp();
		displayPopMessage("[" + this.path + "] <h3>Tiempo agotado</h3><p>La carga de la imagen ha superado el tiempo máximo.</p>", 'modalDialog_tip');
	},
	done: function(hash, url) {
		if (!this.loading) {
			return;
		}
		if(hash == 'error') {
			displayPopMessage("[" + this.path + "] <h3>Error en la carga</h3><p>Se ha producido un error al subir la imagen. Por favor, prueba de nuevo</p>", 'modalDialog_tip');
		}

		this.hash = hash;
		this.url = url;
		this.loading = false;

		var c = $('image_container');
		var div1 = parent.document.createElement('div');
		var div2 = parent.document.createElement('div');
		var a = parent.document.createElement('a');
		var img = parent.document.createElement('img');
		div1.className = 'float_l pr15 pb8 chand';
		div1.setAttribute('id', 'image-'  + hash);
		a.setAttribute("href", "javascript:void(null)");
        a.onclick = new Function ("parent.changeSelected('"+ hash +"')");
		a.id = "desc-" + hash;
		if ($("image_container").childElements().length > 0) {
			a.innerHTML = "Foto #" + ($("image_container").childElements().length);
		} else {
			a.innerHTML = "Foto principal";
		}
		div2.appendChild(a);

		var divclose = parent.document.createElement('div');
		var imgclose = parent.document.createElement('img');
		divclose.style.cursor = "pointer";
		divclose.style.textAlign = "right";
		divclose.style.width = "62px";

		imgclose.setAttribute('src','/images/xbt_on.gif');
		imgclose.setAttribute('alt','x');
		divclose.appendChild(imgclose);
		divclose.onclick = new Function ("parent.deleteImage('uploadform', '" + hash + "') ");
		div1.appendChild(divclose);

		img.setAttribute('src', url);
		img.setAttribute('width', '60');
		img.setAttribute('name', hash );
		img.setAttribute('id', hash );
		img.onclick = new Function ("parent.changeSelected('"+ hash +"')");
		img.className =  "uploaded_image";
		div1.appendChild(img);
		div1.appendChild(div2);
		c.appendChild(div1);
		parent.addImage('uploadform', hash);

		clearTimeout(this.timer);
		this.cleanUp();
	},
	cancel: function() {
		this.loading = false;
		this.timer = 0;
		clearTimeout(this.timer);
		this.cleanUp();
	},
	cleanUp: function() {
		countImages('img_counter');

		if(ImageUpload.areImagesUploading() == 0) {
			$$('.loading').invoke('hide');
		}
		if (this.frame) {
			$('uploaders').removeChild(this.frame);
		}
	}
};

ImageUpload.areImagesUploading = function() {
	var counter = 0;
	for(var i = 0; i < document.uploads.length; i++) {
		if (document.uploads[i].isLoading()) counter++;
	}
	return counter;
}

ImageUpload.cancelUploads = function() {
	for(var i = 0; i < document.uploads.length; i++) {
		if (document.uploads[i].isLoading()) document.uploads[i].cancel();
	}
}

function countImages (divc) {
	var d = $(divc)
	var count_ul = $$('.uploaded_image');
	var count_sel = $$('.uploaded_image_selected');
	var count_img = count_ul.length + count_sel.length;
	if( count_img > 0) {
		d.show();
		d.innerHTML = count_img + " im&aacute;genes cargadas.";
	} else {
		d.hide();
	}
	$('num_img_left').innerHTML = max_images - count_img;
}

/************ Google Maps ************/
    var map = null;
    var geocoder = null;
    var address = null;
	var country = "ES, España";
	var full = "";

    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(40.5202333,-3.6602611), 13);
        map.addControl(new GLargeMapControl);
		map.disableDragging();
        geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode("ES");
      }
    }

     function showAddress(response) {
     	map.clearOverlays();
       	if (!response || response.Status.code != G_GEO_SUCCESS && response.Status.code != G_GEO_UNKNOWN_ADDRESS) {
			switch (response.Status.code) {
				case G_GEO_BAD_REQUEST: // No se ha podido analizar correctamente la solicitud de ruta. Por ejemplo, la solicitud se puede haber rechazado si contenía más del número máximo de hitos permitidos.
					break;
				case G_GEO_SERVER_ERROR: // No se ha podido procesar correctamente la solicitud de ruta o de códigos geográficos, sin saberse el motivo exacto del fallo.
					break;
				case G_GEO_MISSING_QUERY: // = 601 	Falta el parámetro HTTP q o no tiene valor alguno. En las solicitudes de códigos geográficos, esto significa que se ha especificado una dirección vacía. En las solicitudes de ruta, esto significa que no se ha especificado ninguna consulta.
					break;
				case G_GEO_MISSING_ADDRESS: //= 601 	Sinónimo de G_GEO_MISSING_QUERY.
					break;
				case G_GEO_UNKNOWN_ADDRESS: //= 602 	No se ha encontrado una ubicación geográfica que se corresponda con la dirección especificada. Esto puede deberse a que la dirección sea relativamente nueva o a que no sea correcta.
					break;
				case G_GEO_UNAVAILABLE_ADDRESS: //= 603 	El código geográfico de la dirección indicada o de la ruta para la consulta de ruta proporcionada no puede devolverse por motivos jurídicos o contractuales.
					break;
				case G_GEO_UNKNOWN_DIRECTIONS: // 604 	El objeto GDirections no pudo calcular la ruta entre los puntos mencionados en la consulta. Esto suele deberse a que no hay ninguna ruta disponible entre los dos puntos o a que no tenemos datos para extraer rutas en la región en cuestión.
					break;
				case G_GEO_BAD_KEY: //= 610 	La clave proporcionada no es válida o no coincide con el dominio para el cual se ha indicado.
					break;
				case G_GEO_TOO_MANY_QUERIES: //= 620 	La clave especificada ha superado el límite de solicitudes en un período de 24 horas o ha enviado demasiadas solicitudes en un período de tiempo demasiado breve. Si vas a enviar varias solicitudes en un bucle o en un período de tiempo muy reducido, utiliza un temporizador o pausa tu código para asegurarte de que no envías las solicitudes demasiado rápido.
					break;
				default:
					alert("Status Code:" + response.Status.code);
				break;
			}
       } else {
		 var place_array = [];
		 Zip = new RegExp(/\d{5}/);
		 // Accuracy check. Not all results are valid.
		 if ( response.Placemark ) {
			 if (response.Placemark.length > 1) {
				for(j=0; j<response.Placemark.length; j++) {
					if(response.Placemark[j].AddressDetails != undefined  ){
						if(response.Placemark[j].AddressDetails.Accuracy > min_accuracy && Zip.match(response.Placemark[j].address.toString()) ) {
							place_array.push(response.Placemark[j]);
						}
					}
				 }
			 }
		 }
         var street_name = $('st_name');
	   	 if (place_array.length > 1 || response.Status.code == G_GEO_UNKNOWN_ADDRESS ) {
			// Centered in postal code and draggable!
			$('map_suggest').show();
			$('map_suggest_text').innerHTML =
				"<p><span class='bold'>No hemos podido validar tu dirección. Prueba a introducirla de nuevo o a mover el marcador hasta el punto preciso. </span> </p>" +
				"<p><span class='bold'>Tambien puedes usar sólo tu código postal</span>" +
				"<br /><br /><a href='javascript:void(0)' onclick='cleanLocationData(); validateAddressInMap(\"only_zip\");'> " + $('zipcode').value + ", " + country + "</a>" +
				"</p>";
            point = new GLatLng(40.4167,-3.70327);
			if($('map_suggest')) {
				if($('map_suggest').style.display != 'none')  {
					var marker = new GMarker(point,  {draggable: true});
					storeLocationData(street_name ? street_name.value : null, point);
					GEvent.addListener(marker, "dragstart", function() { map.closeInfoWindow(); });
					GEvent.addListener(marker, "dragend", function() { onMarkerDragEnd(map, marker.getPoint()) });
					map.addOverlay(marker);
                    map.setCenter(point);
					return;
				}
			}
			bounds = new GLatLngBounds();
			var givenRad = 1;
			var givenQuality = 40;
			var centre = point || map.getCenter();
			drawCircle(centre, givenRad, givenQuality);
			storeLocationData("", point);
		 } else {
			place = response.Placemark[0];
	 		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
	 		if(response.Placemark[0].AddressDetails.Accuracy > 5){
				$('map_suggest').show();
				storeLocationData(street_name ? street_name.value : null, point);
				$('map_suggest_text').innerHTML =
					"<p><span class='bold'>¿Te refires a esta direcci&oacute;n?</span> " +
					"<br /><br /> " +
					"<a href='javascript:void(0)'  onclick='chooseSuggestedAddress(\"" +place.address + "\")' >" + place.address + "</a>" +
					"</p>" +
					"<p> Si la localización no es exacta puedes arrastrar el marcador por el mapa.</p>" +
					"<p><span class='bold'>No gracias, usaré sólo el código postal</span>"+
					"<br /><br /><a href='javascript:void(0)' onclick='cleanLocationData(); validateAddressInMap(\"only_zip\");'> " + $('zipcode').value + ", " + country + "</a>" +
					"</p>";
				map.setCenter(point, 15);
				bounds = new GLatLngBounds();
				var givenRad = 0.5;
				var givenQuality = 40;
				var centre = point || map.getCenter();
				var marker = new GMarker(point,  {draggable: true});
				// listeners
				GEvent.addListener(marker, "dragstart", function() { map.closeInfoWindow(); });
				GEvent.addListener(marker, "dragend", function() { onMarkerDragEnd(map, marker.getPoint()) });
				map.addOverlay(marker);
			}else{
				map.setCenter(point, 14);
				storeLocationData("", point);
				var givenRad = 1;
				var givenQuality = 40;
				var centre = point || map.getCenter();
				drawCircle(centre, givenRad, givenQuality);
			}
		}
       }
     }

    function onMarkerDragEnd(map, point) {
		map.setCenter(point, 15);
		$('latlong').value = point;
        var street_name = $('st_name');
		storeLocationData(street_name ? street_name.value : '', $('latlong').value);
	}

    function showAddressInMap(address, zip) {
        if(address != undefined && address != null && address != ''){
            if (geocoder){
                var search = address + (zip != undefined && zip != null && zip != '' ? ", " + zip : "") + ", " + country;
                geocoder.getLocations(search, showAddress);
            }
        }
        else if (zip != undefined && zip != null && zip != "") {
            var _parameters = {zipcode:zip} ;
            var opt = {
                method:'GET',
                asynchronous:true,
                parameters:_parameters,
                onComplete:function(t) {
                    try{
                        var data = eval(t.responseText);
                        if(data.length != 2){
                            map.clearOverlays();
                            displayPopMessage('<h3>Codigo Postal incorrecto</h3><p>Por favor, introduce correctamente tu c&oacute;digo postal <br /><br /> Puedes consultar tu c&oacute;digo postal <a href="http://www.correos.es/contenido/13-MenuRec2/04-MenuRec24/1010_s-CodPostal.asp" target="_blank">aquí </a></p>','modalDialog_tip', 400, 150);
                            try{$('zipcode').value = '';}catch(ignore){}
                        }
                        else{
                            var point = new GLatLng(data[0],data[1]);
                            map.setCenter(point, 14);
                            storeLocationData("", point);
                            var givenRad = 1;
                            var givenQuality = 40;
                            var centre = point || map.getCenter();
                            bounds = new GLatLngBounds();
                            drawCircle(centre, givenRad, givenQuality);
                        }
                    }
                    catch(ignore){}
                }
            };
            new Ajax.Request('/getZipcodeGeoloc', opt);
        }
    }

/************ Google Maps End************/

function expand(module, action){
	var action_btn = document.getElementById('action_btn_'+ module);
	if(action=="expand"){
		$('content-step-1-'+ module).style.display="block";
		action_btn.innerHTML = '<a href="javascript:expand(\''+ module +'\', \'collapse\');" >collapse</a><br />';
	} else if (action=="collapse"){
		$('content-step-1-'+ module).style.display="none";
		action_btn.innerHTML = '<a href="javascript:expand(\''+ module +'\', \'expand\');" >expand</a><br />';
	}else{
		alert('error')
	}
}

String.prototype.repeat = function(l){
	return new Array(l+1).join(this);
};

function js2String(obj, indent) {
	if (!indent) indent = 0;
	if (typeof(obj) == 'object') {
		var resp = " ".repeat(indent) + "{\n";
		var i;
		for (i in obj) {
			resp += " ".repeat(indent) + i + ": " + js2String(obj[i], indent+1) + "\n";
		}
		resp += " ".repeat(indent) + "}";
		return resp;
	} else if (typeof(obj) == 'function') {
		return " ".repeat(indent) + '<func>';
	} else {
		return " ".repeat(indent) + obj;
	}
}

function onKeyDownField(e, obj) {
	var keynum;
	if(window.event) { // IE 
  		keynum = e.keyCode;
  	}
	else if(e.which) { // Netscape/Firefox/Opera
  		keynum = e.which;
  	}
	if (keynum == "13"){
		if(obj.id == "zipcode") {
			 onChangeField(obj)
		}
	}	
}

function setProvByZip(obj) {
	var zip = obj.value;
    nZip = zip.replace(/^\s*|\s*$/g,"");
	if (nZip.length == 4)
        nZip = '0' + nZip;
    if(nZip != zip){
        zip = nZip;
        obj.value = zip;
    }
	if (zip.length > 1) {
		var provId = zipcode[zip.substr(0, 2)];
		if (provId) {
			$('provincia').innerHTML = google_maps[provId][1];
			$('provincia_id').value = google_maps[provId][2];
			return true;
		}
        else{
			$('provincia_id').value = "";
		}
	}
    $('provincia').innerHTML = " ";
	return false;
}

function onChangeField(obj) {
	switch (obj.id) {
		case "zipcode":
			if(setProvByZip(obj) == true && obj.value && obj.value.length == 5) {
				cleanLocationData();
				validateAddressInMap("only_zip");
			}  else {
				displayPopMessage('<h3>Codigo Postal incorrecto</h3><p>Por favor, introduce correctamente tu c&oacute;digo postal <br /><br /> Puedes consultar tu c&oacute;digo postal <a href="http://www.correos.es/contenido/13-MenuRec2/04-MenuRec24/1010_s-CodPostal.asp" target="_blank">aquí </a></p>','modalDialog_tip', 400, 150);
				obj.value = "";
				map.clearOverlays();
			}
			break;
		case "chk_address":
			validateAddressInMap();
			break;
		default: break;
	}
}


function cleanLocationData () {
	if($('st_name')) $('st_name').value='';
	if($('address_full')) $('address_full').value = '';
	if($('address_input')) $('address_input').hide();
	if($('map_suggest')) {
		$('map_suggest_text').innerHTML="";
		$('map_suggest').hide();
	}
	if($('latlong')) $('latlong').value='';
}

function storeLocationData (address, point) {
	var full = ((address == '' || address == undefined) ? '' : address + ', ') + $('zipcode').value + ", " + country; ;
	if($('address_full')) $('address_full').value = full;
	if($('latlong')) $('latlong').value=point;
}

function validateAddressInMap (search_type, opt) {
	var zipcode = $('zipcode').value;
	switch(search_type) {
		// Full user address search
		case 'full_user':
			showAddressInMap($("st_name").value, zipcode);
			break;
		// Full google address search
		case 'full_goo':
			showAddressInMap($("st_name").value, zipcode);
			break;
		// Will not use any address or zipcode. Circle will be drawn in the center of the map.
		case 'center_circle':
    	 	map.clearOverlays();
			var centre = map.getCenter();
			map.setCenter(centre, 14);
			bounds = new GLatLngBounds();
			var givenRad = 1;
			var givenQuality = 40;
			drawCircle(centre, givenRad, givenQuality);
			break;
		case 'center_marker':
	     	map.clearOverlays();
			if(opt) {
				var loc = new GLatLng(opt[0],opt[1]);
				map.setCenter(map.getCenter(), 15);
				var marker = new GMarker(loc,  {draggable: true});
				GEvent.addListener(marker, "dragstart", function() { map.closeInfoWindow(); });
				GEvent.addListener(marker, "dragend", function() { onMarkerDragEnd(map, marker.getPoint()) });
				map.addOverlay(marker);
			} else {
				showAddressInMap("", zipcode);
			}
			break;			
		// centered on zipcode.
		case 'drag_zip':
		case 'only_zip':
		default:
			showAddressInMap("", zipcode);
			break;
	}
	return;
}

function chooseSuggestedAddress (addr, lat, long) {
	var addr_results = addr.split(',');
    var street_name = $('st_name');
    if(street_name)
	    street_name.value = addr_results[0];
	validateAddressInMap("full_goo");
}

function onChangeContactPhone(txtFieldObj, chkFieldName){
	var chkFieldObj = $(chkFieldName);
	chkFieldObj.disabled = (txtFieldObj.value == '');
	if(chkFieldObj.disabled && chkFieldObj.checked)
		chkFieldObj.checked = false;
}

function onBeforeSubmitPost(chkFieldName, txtFieldName, targetHdnField, defValue, phnOnlyValue, bothValue){
	if($(chkFieldName).checked){
		$(targetHdnField).value = phnOnlyValue;
	}
	else{
		if($(txtFieldName).value == ''){
				$(targetHdnField).value = defValue;
		}
		else{
				$(targetHdnField).value = bothValue;
		}
	}
}