﻿/* Copyright adprecision Ltd 2009
None of this script is to be copied or distributed without prior written consent from adprecision Ltd
www.adprecision.net
*/

// Symeon Breen, adprecision ltd Oct 2009

// assumes jquery, gmaps

// Globals
var dropcnt = 1;
var now = new Date();
var map = '';
var geocoder = '';
var JSON = JSON || {};

// Globals overridden in page with values from backend
var faveidsTbl = ''; // list ads in faves - associatice array with object values
var addetail = ''; // all ads on page with details in object - associative array
var mapData = '';

//onload
if (!(typeof (jQuery) == 'undefined')) {
    $(document).ready(function() {
        if (objLen(faveidsTbl)) $("#favesave").css("display", "block");
        $(".rowo,.rowe").draggable({ opacity: 0.7, helper: 'clone' });
        $("#favedrop").droppable({
            tolerance: 'touch',
            drop: function(event, ui) {
                //var adId = geturivar($(ui.draggable).find("div[class='col1']").find("a").attr("href"), "ag");
                var adId = $(".col3", ui.draggable).find("a").attr("href")
                if (adId == "#" || adId == "" || typeof (adId) === undefined) {
                    var dd = $(".col3", ui.draggable).find("a").get(0);
                    adId = geturivar(dd.getAttribute("onclick").tostr().replace("javascript:window.open('", ""), "ag");
                }
                else {
                    adId = geturivar(adId, "ag");
                }
                if (adId.substr(0, 4) == 'http' || adId.substr(0, 4) == 'b64:') {
                    alert("Sorry you can not save our Partner site ads in here");
                }
                else {
                    if (adId != "") {
                        if (typeof (faveidsTbl[adId]) == 'undefined') {
                            detail = addetail[adId];
                            if (detail == "" || typeof (detail) == "undefined" || detail == false) detail = new Array();
                            detail["dropid"] = dropcnt;
                            faveidsTbl[adId] = detail;
                            var cclas = "dropped";
                            if ($(".col2", ui.draggable).length == 0) cclas = "artdropped";
                            $("#favesave").css("display", "block");
                            $('<span class="favebreak"></span><div id="drop' + dropcnt + '" class="' + cclas + ' rowe">' + ui.draggable.html() + '<div class="col99"><a onClick="delFave(' + "'#drop" + dropcnt + "','" + adId + "'" + ')" href="#">Delete</a></div></div>').appendTo($(this));
                            dropcnt++;
                        }
                    }
                }
            }
        });
    });
}
// functions


function delFave(divid, adid) {
    $(divid).remove();
    delete faveidsTbl[adid];
    if (objLen(faveidsTbl) == 0) $("#favesave").css("display", "none");
}

function objLen(obj) {
    if (obj.__count__ === undefined) {
        var cc = 0;
        for (oo in obj) if (obj.hasOwnProperty(oo)) cc++;
        return cc;
    }
    else {
        return obj.__count__;
    }
}
function favesave(t) {

    var favesaves = new Object;
    for (var ad in faveidsTbl) {
        favesaves[ad] = faveidsTbl[ad]["dropid"] + " ";
    }

    var dd = "u=" + t.inp_uniqueID.value + "&m=S&j=" + JSON.stringify(favesaves) + "&h=" + encodeURIComponent($("#favedrop").html());
    
       
    $.ajax({
        type: "POST",
        url: "favesave.aspx",
        data: dd,
        success: function(msg) {
            alert("Your choices have been saved");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("An error occured trying to save you choices, please try again later.\n\nError = " + textStatus);
        }
    });

    return false;
}
function favemanage(t) {
    // html factory for favourites display
    $("#favecontent").html('') 
    $("#favecompare").css("display", "block");
    var template = $("#favecomparetemplate").html();
    var newrow = "";
    var s = ""
    var adid = ""
    var flyfields = ""
    var thisad = ""
    var i = 0;
    var adsummary = new Object();
    for (var ad in faveidsTbl) {
        i++;
        thisad = faveidsTbl[ad]
        if (thisad["dropid"] != "") {
            var adsummaryinner = new Object()
            var favehtml = $("#drop" + thisad["dropid"]);
            adsummaryinner['Title'] = $("span.Title", favehtml).text();
            if (adsummaryinner['Title'] == "") adsummaryinner['Title'] = $(".col2 h3 a", favehtml).text();
            if (adsummaryinner['Title'] == "") adsummaryinner['Title'] = $(".col2 h2 a", favehtml).text();
            if (adsummaryinner['Title'] == "") adsummaryinner['Title'] = $(".col2 h4 a", favehtml).text();
            newrow = template.replace("%col1%", $(".col1", favehtml).html());
            newrow = newrow.replace("%col2%", $(".col2", favehtml).html());
            flyfields = ""
            for (var ff in thisad) {
                if (ff != "dropid") {
                    if (thisad[ff] != "") flyfields += "<span>" + thisad[ff] + "</span>";
                    adsummaryinner[ff] = thisad[ff];
                }
            }
            newrow = newrow.replace("%comparefields%", flyfields);
            $("#favecontent").append(newrow);
            adsummary[ad] = adsummaryinner;
        }
    }
    var t = '';
    var th = '<tr>';
    var doneth = false;
    try {
        for (var ad in adsummary) {
            t += '<tr>'
            for (ff in adsummary[ad]) {
                if (!doneth) th += '<th>' + ff + '</th>';
                t += '<td>' + adsummary[ad][ff] + '</td>';
            }
            t += '</tr>';
            doneth = true
        }
    }
    catch (ee) { alert(ee) }
    th += '</th>';
    $("#favecontent").append('<span id="favesummary">Summary<table>' + th + t + '</table></span>');
    t += '</table>'
    return false;

}
function closefavemanage(t) {
    $("#favecontent").html('')
    $("#favecompare").css("display", "none");
}
 function geturivar(uristring, varname) {
    varname = varname.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + varname + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(uristring);
    if (results == null) {
        return "";
    }
    else {
        return results[1];
    }
}

function createMarker(address, html, zz, plot, ispoint) {
    if (ispoint) {
        var marker = new GMarker(GLatLng.fromUrlValue(address));
        map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() {
            //marker.openInfoWindowHtml(html);
            window.location = html;
        });
    }
    else {
        geocoder.getLatLng(
                    address,
                    function(point) {
                        if (!point) {
                            //alert(address + " not found");
                        } else {

                            if (plot) {
                                var marker = new GMarker(point);
                                map.addOverlay(marker);
                                GEvent.addListener(marker, "click", function() {
                                    //marker.openInfoWindowHtml(html);
                                    window.location = html;
                                });
                            } else {
                                map.setCenter(point, zz);
                            }
                        }
                    });
    }

}


function doMaps() {
    // Display the map
    map = new GMap2(document.getElementById("themap"));
    map.addControl(new GMapTypeControl());
    map.addControl(new GSmallZoomControl3D());
    geocoder = new GClientGeocoder();
    //createMarker('uk', '', 5, false, false);
    createMarker(mapData.Location, '', parseInt(mapData.Zoom), false, false);
    //map.setCenter(new GLatLng(54.52108, -3.208), 5);
    
    if (!(typeof(mapData.Places) == 'undefined')) {
        var html = '';
        maxPoints = mapData.Places.length
        for (var i = 0; i < maxPoints; i++) {
            html = mapData.Urls[i] + ".xhtml";
            createMarker(mapData.Places[i], html,parseInt(mapData.Zoom), true, mapData.isPoint[i]);
        }
    }
}


function showMore(c) {

    document.getElementById("more" + c).style.display = "block";

}

function hideMore(c) {

    document.getElementById("more" + c).style.display = "none";

}
function popunder(url) {
    if (url != "") {
        var newwin = window.open(url);
        newwin.blur();
        window.focus();
    };
}
function adprs__doPostBack(eventTarget, eventArgument) {
    var thisForm = document.forms['form1'];
    if (!thisForm) {
        thisForm = document.form1;
    }
    thisForm.adprs_sysid.value = thisForm.thissysid.value;
    __doPostBack(eventTarget, eventArgument);
}

JSON.stringify = JSON.stringify || function (obj) { 
// ie8,ff,chrome have JSON others do not so set func to serialise
	    var t = typeof (obj); 
	    if (t != "object" || obj === null) { 
	        if (t == "string") obj = '"'+obj+'"'; 
	        return String(obj); 
	    } 
	    else { 
	        var n, v, json = [], arr = (obj && obj.constructor == Array); 
	        for (n in obj) { 
	            v = obj[n]; t = typeof(v); 
	            if (t == "string") v = '"'+v+'"'; 
	            else if (t == "object" && v !== null) v = JSON.stringify(v); 
	            json.push((arr ? "" : '"' + n + '":') + String(v)); 
	        } 
	        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); 
	    } 
	}; 

Function.prototype.tostr = function() {
    return new String(this);
}
String.prototype.tostr = function() {
    return this;
}
function updateHrefs() {
    flyads = document.getElementById("adprssearchResults");
    if (flyads && document.getElementsByTagName) {
        var anchors = flyads.getElementsByTagName("a");
        for (var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.getAttribute("href", 2) == "#") {
                var click = anchor.getAttribute("onclick").tostr();
                //alert(click);
                if (click) {
                    var index = click.indexOf("http");
                    var inner = anchor.innerHTML
                    if (index) { anchor.href = click.substring(index, click.indexOf("')")); anchor.onclick = ""; anchor.innerHTML = inner };
                }
            }
        }
    }
    doMaps()
}

function showtab(j) {
    var tabul = document.getElementById('tabul');
    var tabli = tabul.getElementsByTagName('li');
    for (var i = 0; i < tabli.length; i++) {
        if (i == j) {
            tabli[i].className = "top"
            tabli[i].getElementsByTagName('a')[0].className = "top";
            document.getElementById(tabli[i].id + "_x").className = "show"
        }
        else {
            tabli[i].className = ""
            tabli[i].getElementsByTagName('a')[0].className = "";
            document.getElementById(tabli[i].id + "_x").className = "hide"
        }
    }
}
function showTab(n, max) {
    for (var i = 1; i <= max; i++) {
        if (i == n) {
            document.getElementById("tabs_" + i).className = "tabshow";
            document.getElementById("tabs_" + i + "_inner").className = "tabshow";
        }
        else {
            document.getElementById("tabs_" + i).className = "tabhide";
            document.getElementById("tabs_" + i + "_inner").className = "tabhide";
        }
    }
}
function kwClick(f) {
    var oth = f.inp_keywords.value;
    if (oth.substring(0, 5) == "e.g. ") { f.inp_keywords.value = "" }
}
function hkwClick(f) {
    var oth = f.keywords.value;
    if (oth.substring(0, 5) == "e.g. ") { f.keywords.value = "" }
}

function pcodeClick(f) {
    var oth = f.postcode.value;
    if (oth == "Postcode") { f.postcode.value = "" }
}
function butsubmit(f, n) {
    f.butSubmit.value = n;
}
function dopaging(pageno, id, max) {
    showLoading();
    $("#adprssearchResults").load("pager.aspx?no=" + pageno + "&id=" + id + "&max=" + max, "", function() {
        var Path = window.location.pathname;
        var Page = Path.substring(Path.lastIndexOf('/') + 1);
        pageTracker._trackPageview("/" + Page);
    });
}

function showLoading() {
    document.getElementById("adprssearchResults").innerHTML = '<br/><img src="images/loading.gif" style="padding-left:200px">';
}

