function isPositiveInteger(s) {
  return s.toString().search(/^[0-9]+$/) == 0;
}

function _loadRangeAttr(filtro, urlbase, el1, el2) {
	if(!el1 || !el2)
        return false;
	var el_min = document.getElementById(el1).value;
	var el_max = document.getElementById(el2).value;
	if (el_min == '' || !isPositiveInteger(el_min))
		el_min = "0";

	if (el_max == '' || !isPositiveInteger(el_max))
		el_max = "2100000000";

	// TODO: Check if there's a backslash at the end
	window.location = urlbase + filtro + ":" + el_min + ":" + el_max + "/";
	return false;
}

function _loadTextAttr (el, base_url) {
	var el_text = document.getElementById(el).value;
    if(el_text == "" || el_text == null) return;
	location.href = base_url + el_text + "/";
}
function _loadTextAttr_hp (el, _domain_counter) {
	var el_text = document.getElementById(el).value;
    if(el_text == "" || el_text == null)
        return false;

    var success = function() {
        location.href = encodeURI(el_text) + "/";
    };

    var qs = '?grp=SB&ftxt=' + encodeURI(el_text);
    new Ajax.Request(_domain_counter + '/counter.gif' + qs, {
      method: 'get',
      onSuccess: success
    });

    //Timeout, just in case
    setTimeout(success, 2000);
    return false;
}

function addVisitedPosts(post_id, limit) {
	var currentPosts = getCookie("visited_posts");
	if (currentPosts == null) {
		currentPosts = post_id;
	} else {
		currentPosts = post_id + "," + currentPosts.split(",").without(post_id, "").slice(0, limit-1).join(",");
	}
	setCookie("visited_posts", currentPosts, "/");
}

function removeLastVisitedAd(post_id) {
	var currentPosts = getCookie("visited_posts");
	if (currentPosts == null) {
		return;
	}
	currentPosts = currentPosts.split(",").without(post_id, "").join(",");
	setCookie("visited_posts", currentPosts, "/");
	window.location.reload();
}

function toggleFavoritePosts(post_id) {
	var currentPosts = getCookie("favorite_posts");
	if (currentPosts == null) {
		addFavoritePosts(post_id);
		return;
	}
	if (currentPosts.split(",").indexOf(post_id) > -1) {
		removeFavoritePosts(post_id);
	} else {
		addFavoritePosts(post_id);
	}
}

function addFavoritePosts(post_id) {
	var currentPosts = getCookie("favorite_posts");
	if (currentPosts == null) {
		currentPosts = post_id;
	} else {
		currentPosts = post_id + "," + currentPosts.split(",").without(post_id, "").join(",");
	}
	setCookie("favorite_posts", currentPosts, "/");
	//$("fav_img_" + post_id).src = "/images/star01.gif";
    var adObj = $("fav_img_" + post_id);
    if(adObj){
    	adObj.className = adObj.className.replace("favorite_post_off", "");
	    adObj.className += " favorite_post_on";
    }
	if ($("favorites_container")) {
		new Ajax.Updater( {success: "favorites_container"}, "/getFavorites");
	}
	updateNumberOfFavorites();
}

function updateNumberOfFavorites() {
    var objFavPost = $("numberFavoritesPost");
	if (objFavPost) {
		var currentPosts = getCookie("favorite_posts");
		var number = 0;
		if (currentPosts != null && currentPosts != "") {
			number = currentPosts.split(",").length;
		}

        objFavPost.update(number);
        var favTxtContainer;
		if (number == 0) {
            //remove a
			$("divFavorites").hide();
            favTxtContainer = $("favTxtContainer");
            if(favTxtContainer && favTxtContainer.children[0].tagName.toUpperCase() == 'A'){
                favTxtContainer.innerHTML = favTxtContainer.children[0].innerHTML;
            }
		}
        else {
            if(number == 1){
                //insert a if doesn't exist (2 favorites remove 1 -> A exists, 0 favorites add 1 -> A doesn't exist)
                favTxtContainer = $("favTxtContainer");
                if(favTxtContainer && favTxtContainer.children[0].tagName.toUpperCase() != 'A'){
                    favTxtContainer.innerHTML = "<a href=\"#favoriteAdsAnchor\">" + favTxtContainer.innerHTML + "</a>";
                }
            }
			$("divFavorites").show();
		}
	}
}

function toggleVisibility(elem) {
	var offsets = document.viewport.getScrollOffsets();
	elem.style.top = offsets[1] + 100 + "px";
	if (elem.style.display == "none") {
		elem.show();
	} else {
		elem.hide();
	}
}

function removeFavoritePosts(post_id) {
	var currentPosts = getCookie("favorite_posts");
	if (currentPosts == null) {
		return;
	}
	currentPosts = currentPosts.split(",").without(post_id, "").join(",");
	setCookie("favorite_posts", currentPosts, "/");
    var adObj = $("fav_img_" + post_id);
    if(adObj){
	    //adObj.src = "/images/star02.gif";
        adObj.className = adObj.className.replace("favorite_post_on", "");
        adObj.className += " favorite_post_off";
    }
	if ($("favorites_container")) {
		new Ajax.Updater( {success: "favorites_container"}, "/getFavorites");
	}
	updateNumberOfFavorites();
}

var ___searching_lock = false;
function doBrowseSearch(form, _domain_counter) {
    if(___searching_lock === true)
        return false;
    
    ___searching_lock = true;
	var txt = form._nkw.value;
	var category = form._sacat.options[form._sacat.selectedIndex].value;
	var loc = form._saprov.options[form._saprov.selectedIndex].value;
	var url = '/';
    var isTS = txt != '';
    var qs = isTS ? '?grp=SB&ftxt=' + encodeURI(txt) : null;

    if (loc != ''){
        url += loc + '/';
        if(isTS){
            var floc = form._saprov.options[form._saprov.selectedIndex].id;
            if(floc != '')
                qs += '&floc=' + floc.substring('_saprov_'.length);
        }
    }

    if (category != ''){ 
        if(category.charAt(0) == '/')
            url += category.substring(1);
        if(url.charAt(url.length - 1) != '/')
            url += '/';

        if(isTS){
            var cat = form._sacat.options[form._sacat.selectedIndex].id;
            if(cat != ''){
                var fcatl1 = cat.substring('_sacat_'.length);
                var fcatl2 = '';
                var pos = fcatl1.indexOf('|');
                if(pos != -1){
                    fcatl2 = fcatl1.substring(pos + 1);
                    fcatl1 = fcatl1.substring(0, pos);
                }
                qs += '&fcatl1=' + fcatl1;
                if(fcatl2 != '')
                    qs += '&fcatl2=' + fcatl2;
            }
        }
    }

	if (txt != '')
        url += encodeURI(txt) + '/';
	else if (url == '/')
        url = '/todos/';

    var success = function(transport) {location.href = url;};
    
    if(isTS){
        new Ajax.Request(_domain_counter + '/counter.gif' + qs, {
          method: 'get',
          onSuccess: success
        });
    }

    //Timeout, just in case
    setTimeout(success, 2000);
	return false;
}

function mustShowSecurityAlert(){
    var currentPosts = getCookie("ebaycoches_securwarn");
    return currentPosts == null;
}

function notAgainSecurityAlert(checkbox){
    if(!checkbox || (typeof checkbox.checked == 'undefined') || checkbox.checked)
        setCookie("ebaycoches_securwarn", "N", "/", 1296000000);
}

function sendEmailMessageToVendor(frm, b, platform_id, extra) {
    if(!$('terms_conditions').checked){
        alert("Es necesario aceptar las condiciones de uso para contactar con el anunciante");
        return;
    }

	if(platform_id == 2 && mustShowSecurityAlert()) {
        if(typeof extra == 'undefined'){
            // Interstitial banner.
            var msg =  "<p style='font-weight:bold;color:#00019C;font-size:16px;'>Alerta de Seguridad de ebay coches</p>";
            msg += "<div style='text-align:left;padding-left:15px;'>";
            msg += "<p>Recuerda que:</p>";
            msg += "<p>eBayCoches <u>nunca</u> intermedia en el proceso de compra venta ni colabora con ningún servicio de intermediación.</p>";
            msg += "<p>Si tienes alguna duda, por favor, contacta con nosotros</p>";
            msg += "<p style='padding-top:5px;font-size:9px'><input type='checkbox' onclick='notAgainSecurityAlert(this)'/> No mostrar este mensaje más.</p>";
            msg += "<p style='text-align:center; padding: 5px; border: solid 1px #CCC; background-color: #F3F2F2; font-weight:bold'>";
            msg += "<a href='javascript:sendEmailMessageToVendor(\"" + frm + "\"," + b + "," + platform_id + ", 1)'>ACEPTAR</a></p>";
            msg += "</div>";

            displayStaticMessage(msg, "modalDialog_sec_notice", 400, 215);
            return;
        }
	}
    sendEmailMessage(frm, b);
}


/************************ Funtions for MAIL ************************/

function sendEmailMessage(frm, useForm) {
	var f = $(frm);
	f["_qs"].value = f.serialize();
	if (useForm == 'false') {
		new Ajax.Request(f.getAttribute("action"), {
			"method": "post",
			"postBody": "_qs=" + f.serialize(),
			"onSuccess": function(t) { receiveEmailMessage(t, f["_opid"].value); }
		})
	} else {
		f.submit();
	}
}

function receiveEmailMessage(t, tipo) {
	if (t.responseJSON != null) {
		r = t.responseJSON;
		switch(tipo) {
			case "umdc":
				if(r.captcha != '' && r.captcha != undefined) {
					$('cvCaptcha').update(r.captcha);
				}
				$("errorMsg").show();
				if (r.err != 0) {
					$("errorMsg").innerHTML = r.err_msg;
				} else {
					if(r.location != '' && r.location != undefined) {
						window.location=  r.location;
						return;
					}
					$('phone_number').value = '';
					$('user_name').value = '';
					$('text').value='';
					$('email').value='';
					$("errorMsg").innerHTML = "<span style='color: #33CC00 !important;'>" + r.err_msg + "</span>";
				}
                break;
			case "cv":
				if (r.err != 0) {
					$("errorMsg").innerHTML = r.err_msg;
					// TODO: recargar el captcha!!!!!!!
				} else {
					$("errorMsg").innerHTML = "<span style='color: #33CC00 !important;'>" + r.err_msg + "</span>";
					$("tdCaptcha").innerHTML = "";
					$("tdCaptchaTxt").innerHTML = "";
					$("tdClose").innerHTML = "";
				}
				$("errorMsg").show();
				break;
			case "stf":
				if (r.trck != undefined && r.trck != '') {
					if($("errorMsgDyn")) {
		               	var scripts = [];
		               	var script_sources = r.trck.split(/<script.*?>/);
              		   	for (var i=1; i < script_sources.length; i++) {
							scripts.push(eval(script_sources[i].split(/<\/script>/)[0]));
					   	}
						$("errorMsgDyn").innerHTML += r.trck;
					}
				}
				if (r.err != 0) {
					if($("errorMsgDyn")) $("errorMsgDyn").innerHTML = r.err_msg;
					$("tdCaptcha").innerHTML = r.captcha;
				} else {
					$("errorMsgDyn").innerHTML = "<span style='color: #33CC00 !important;'>" + r.err_msg + "</span>";
					$("tdCaptcha").innerHTML = "";
					$("tdCaptchaTxt").innerHTML = "";
					$("tdClose").innerHTML = "";
				}
				$("errorMsgDyn").show();
				break;
			default: break;
		}
	}
}

function clearContactFormErrors(){
	if($('errorMsg') && $('errorMsg').children && $('errorMsg').children.length > 0)
		$('errorMsg').hide();
}

/****************** Phone Contact Functions - AJAX based ***********************/

function requirePhoneNumber (p_id) {
	var _parameters = {_pid:p_id, _opid:3};
	var opt = {
		method:'post',
		parameters:_parameters,
		evalJS: 'force',
		onComplete:function(t) { showPhoneNumber(t); }
	};
	new Ajax.Request('/content/_content_actions.php', opt);
}

function showPhoneNumber(t) {
	if (t.responseXML != null) {
		var doc = t.responseXML.documentElement;
		if (doc.getElementsByTagName('error')[0].firstChild.nodeValue != 0) {
			$('errorMsg').style.display = "";
			$('errorMsg').innerHTML = doc.getElementsByTagName('text')[0].firstChild.nodeValue;
			$('phoneInfo').style.display = "none";
		} else {
			var ph = $('phoneInfo');
			ph.removeAttribute('onclick');
			ph.style.textDecoration = 'none';
			ph.update("<span class='icon_red04 size12'>" + doc.getElementsByTagName('text')[0].firstChild.nodeValue+ "<span>");
		}
	}
}


/*******************************************************************************/

function m_over (id) {
	var e = document.getElementById(id);
	e.style.color="#F00";
	e.style.textDecoration="underline";
}

function m_out (id) {
	var e = document.getElementById(id);
	e.style.color="";
	e.style.textDecoration="";
}

function viewPic (el, hash, alt, index) {
	var idx = (typeof(index)!='number') ? index.substring(index.length-1, index.length) : index;
	window.current_number = idx;

	var _parameters = {h:hash, _opid:2, mode:"big"};
	var src=null;
	var opt = {
		method:'post',
		parameters:_parameters,
		onComplete:function(t) {
			src = t.responseText;
			if(src!=undefined) {
                alt = alt.replace(/\'/g,'\\\'').replace(/\n/g,'').replace(/</g,'&lt;').replace(/>/g,'&gt;');
				img_html = "<div class='of_hid'><img id='big_img' class='big_img' src='" + src + "' alt='" + alt + "' /></div>";
				img_html += "<div class='float_l w630 ml20'><div id='img_bot_popup' class='pt8'>" + $('img_bot').innerHTML + "</div></div><div class='float_r pt8'><a href='javascript:void(null)' onClick='closeMessage()'>Cerrar</a></div>";
				displayStaticMessage(img_html, "modalDialog_img", 690, 535);
				selectPic(src, 'big_img', alt, idx);
			}
		}
	};
	new Ajax.Request('/content/_content_actions.php', opt);
}

function prevPic() {
	var i = parseInt(window.current_number) - 1;
	if ($("ph" + i) != null)
		selectPic($("ph" + i).getAttribute("imageurl"), 'big_img', '', i);
}

function nextPic() {
	var i = parseInt(window.current_number) + 1;
	if ($("ph" + i) != null)
		selectPic($("ph" + i).getAttribute("imageurl"), 'big_img', '', i);
}

function selectPic (idx, el, t, i) {
	$("ph" + i).adjacent("span").each(function(elem){
		elem.removeClassName("remark_img_nav");
	});
	$("ph" + i).addClassName("remark_img_nav");
	$('img_bot_popup').update($('img_bot').innerHTML);
	$(el).src = idx;
	$(el).alt = t + " - Foto " + i;
	window.current_number = i;
}


/***********************************************************************************
EXTERNAL FUNCTIONS
************************************************************************************/
function getCookie(cookieName) {
	var pos=document.cookie.indexOf(cookieName+"=");
	if (pos!=-1){
		var start=pos+cookieName.length+1;
		var end=document.cookie.indexOf(";",start);
		if (end==-1){
			end=document.cookie.length;
		}
		return unescape(document.cookie.substring(start,end));
	}
	return null;
}

function CreateBookmarkLink() {
	var title = document.title;
	var url = location.href;
	if (window.sidebar) { //Firefox
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera
		}
}

function getLuckyNumber() {
	var cn = 'lucky9';
    var date = new Date();
    date.setTime(date.getTime()+(30*24*60*60*1000));
	if (location.href.indexOf("?") > 0) {
		var url = location.href.split("?")[1].split("&");
		if (typeof(url) != "undefined") {
			for (var i=0; i<url.length; i++) {
				var v = url[i].split("=");
				if (typeof(v) != "undefined" && v[0] == cn) {
					document.cookie = cn+"="+v[1]+"; expires="+date.toGMTString()+"; path=/; domain="+gCookieDomain+";";
				}
			}
		}
	}
	var ln = getCookie(cn);
	if (ln == null) {
		ln = "" + Math.floor(Math.random()*9999999);
		ln = Array(8 - ln.length).join("0") + ln;
		document.cookie = cn+"="+ln+"; expires="+date.toGMTString()+"; path=/; domain="+gCookieDomain+";";
	}
	return ln.substring(ln.length - 2);
}

function setLN(obj) {
	var cn = 'lucky9';
	getLuckyNumber();
	var ln = getCookie(cn);
	if (obj.indexOf("?") > 0) {
		if (obj.indexOf(cn) > 0) {
			var aUrl = obj.split("?");
			var url = aUrl[0] + "?";
			var aParams = aUrl[1].split("&");
			for (var i=0; i<aParams.length; i++) {
				elem = aParams[i].split("=");
				if (elem[0] != cn) {
					url += aParams[i] + "&";
				}
			}
			obj = url + cn + "=" + ln;
		} else {
			obj = obj + "&" + cn + "=" + ln;
		}
	} else {
		obj = obj + "?" + cn + "=" + ln;
	}

	return obj;
}


/******************************************* LOQUO JS ************************************/
function setCaptchaResp(val, field) {
	setOnLoad(field == "" ? 'CaptchaStr' : field, val);
}

function setOnLoad(id, val) {
	var o = document.getElementById(id);
	if (o)
        o.value = val;
	else setTimeout("setOnLoad('" + id + "', '" + val + "')", 200);
}

function setCookie(cookieName, cookieValue, path, expiration) {
	var expire = new Date();
    if(!expiration)
        expiration = 3600000*24*365;
	expire.setTime(expire.getTime() + expiration);
	cookieString = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
	if (path != null) {
		cookieString += ";path=" + escape(path);
	}
	document.cookie = cookieString;
}

function requireContent (id, key, type, w, h) {
	var _parameters = {k:key, _opid:1, _pid:id, type:type, captcha_needed:1};
	var opt = {
		method:'post',
		parameters:_parameters,
		onComplete:function(t) {
			switch (type) {
				case "share":
					showDialog(t, "modalDialog_share");
					break;
				case "error":
				case "alert":
				default:
					showDialog(t, "modalDialog_tip");
			}
		}
	};
	new Ajax.Request('/content/_content_actions.php', opt);
}

function showDialog (content, cl, w, h) {
	if (content.responseText != null) {
        if(w == null)
            w = 550;
        if(h == null)
            h = 300;
		displayStaticMessage(content.responseText, cl, w, h, true);
	}
}

function markAsSold(post_id) {
    markAs(post_id, 4);
}

function markAsSpam(post_id) {
    markAs(post_id, 2);
}

function markAsForbiden(post_id) {
    markAs(post_id, 3);
}

function markAsMiscat(post_id) {
    markAs(post_id, 1);
}

function markAs(post_id, op) {
	var url = "/review/review.php";
	new Ajax.Request(url, {
		method: "post",
		postBody: "post_id=" + post_id + "&review=" + op,
		onSuccess: function(transport) {
			var reviewBar = $("reviewBar");
			reviewBar.update(transport.responseText);
		}
	});
}

/********************************* VIP & PREVIEW specific ************************************/

function requireImage (hash, index, w, h, mode) {
	var _parameters = {h:hash, _opid:2, width:w, height:h, mode:mode};
	var opt = {
		method:'post',
		parameters:_parameters,
		onComplete:function(t) { showImage(t, index, w, h); }
	};
	window.main_image_hash = hash;
	new Ajax.Request('/content/_content_actions.php', opt);
}

function showImage(t, index, w, h) {
	if (t.responseText != null) {
		var doc = t.responseText;
		$('vip_main_pic').update("<img id='main_pic_show' name='imgb_" + index + "'  src='" + doc + "' " + ((w!=null)?" width="+w:" ") + ((h!=null)?" height= "+h:" ") +  " />");
	}
}

function vip_initialize(lat, lon, zoom) {
	if (GBrowserIsCompatible() && lat != '' && lat != null && lat != undefined && lon != '' && lon != null && lon != undefined ) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(lat, lon), zoom);
		map.addControl(new GLargeMapControl);
		var point = new GLatLng(lat, lon);
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() { map.setCenter(marker.getPoint()); });
		if(typeof(dc) != "undefined") {
			if(dc != true) {
				map.setZoom(14);
				bounds = new GLatLngBounds();
				var givenRad = 1;
				var givenQuality = 40;
				drawCircle(map.getCenter(), givenRad, givenQuality);
			}
		} else map.addOverlay(marker);
	}
}

function multiFieldOrder(fieldMapping, fieldAndOrder) {
    var field = fieldAndOrder.charAt(0);
    var order = fieldAndOrder.charAt(1);
    setOrder(fieldMapping[field], order);
}

function setOrder(field,order) {
	scookie = new Cookie({name: 'sort', expires: 0, path: '/'});
	scookie.setData(field + ':' + order);
	location.reload(true);
}

function eliminarSeleccion(url) {
    location.href=url;
}

function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa){
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step){
	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() +
		(radius/lngConv * Math.sin(i * Math.PI/180)));
		points.push(pint);
		bounds.extend(pint);
	}
	points.push(points[0]);
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	map.addOverlay(poly);
}

var _all_provinces_loaded = false;
function showAllProvinces(){
    if(!_all_provinces_loaded){
        var filters = location.href;
        new Ajax.Updater( {success: "all_provinces"}, "/getProvinces?filters=" + encodeURIComponent(filters));
        _all_provinces_loaded = true;
    }

    var carm = $('all_car_makers');
    if(carm)
        carm.hide();
    var prov = $('all_provinces');
    if(prov)
        toggleVisibility(prov);
    return false;
}

var _all_carmanufacturers_loaded = false;
function showCarManufacturers(){
    if(!_all_carmanufacturers_loaded){
        var filters = location.href;
        new Ajax.Updater( {success: "all_car_makers"}, "/getCarManufacturers?filters=" + encodeURIComponent(filters));
        _all_carmanufacturers_loaded = true;
    }

    var prov = $('all_provinces');
    if(prov)
        prov.hide();
    var carm = $('all_car_makers');
    if(carm)
        toggleVisibility(carm);
    return false;    
}