﻿/* Copyright adprecision Ltd 2010,2011
None of this script is to be copied or distributed without prior written consent from adprecision Ltd
www.adprecision.net
*/

// Symeon Breen, adprecision ltd 2010

// 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 = '';
var bigMap = false;
//onload - no auto onload - uses entrypoints for each page - see entryPoint1 etc

// functions

function docReady() {

    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 coltouse = ".col1";
            if ($(".col1", ui.draggable).find("a").length == 0) coltouse = ".col2";
            var adId = $(coltouse, ui.draggable).find("a").attr("href")
            if (adId == "#" || adId == "" || typeof (adId) === undefined) {
                var dd = $(coltouse, 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 {
                adtoFaves(adId, ui.draggable, this);
            }
        }
    });
}

function shortlist(t,adId) {
    var pp = $(t).parents(".rowo, .rowe");
    var fd = $("#favedrop");
    adtoFaves(adId, pp, fd);
    return false;
}

function adtoFaves(adId, JQO, appendJQO) {
    // JQO is a jquery object of dragged or clicked ad
    // appendJQO is a jquery object to append to
    if (adId != "") {
        if (typeof (faveidsTbl[adId]) == 'undefined') {
            var detail = addetail[adId];
            if (detail == "" || typeof (detail) == "undefined" || detail == false) detail = new Array();
            detail["dropid"] = dropcnt;
            faveidsTbl[adId] = detail;
            var cclas = "dropped";
            if ($(".col2", JQO).length == 0) cclas = "artdropped";
            $("#favesave").css("display", "block");
            $('<span class="favebreak"></span><div id="drop' + dropcnt + '" class="' + cclas + ' rowe">' + JQO.html() + '<div class="col99"><a onClick="delFave(' + "'#drop" + dropcnt + "','" + adId + "'" + ')" >Delete</a></div></div>').appendTo($(appendJQO));
            dropcnt++;
            favesave(null);
        }
    }
}

function delFave(divid, adid) {
    $(divid).remove();
    delete faveidsTbl[adid];
    favesave(null);
    if (objLen(faveidsTbl) == 0) $("#favesave").css("display", "none");
    return false;
}

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) {
    if (typeof (t) == 'undefined' || t == null) {
        t = getForm();
    }
    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 your choices, please try again later.\n\nError = " + textStatus);
        }
    });

    return false;
}
function favemanage(t) {
    // html factory for favourites display
    $("#favecontent").html('')
    $("#favecompare").css("display", "block");
    $("#overlay").css("display", "block");
    $("#overlay").css("height", $(document).height());
    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"><p>Summary</p><table>' + th + t + '</table></span>');
    t += '</table>'
    return false;
}
function closefavemanage(t) {
    $("#favecontent").html('')
    $("#favecompare").css("display", "none");
    $("#overlay").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;
    }
    if(!(typeof(thisForm.adprs_sysid) == 'undefined') && !(typeof(thisForm.thissysid) == 'undefined')) thisForm.adprs_sysid.value = thisForm.thissysid.value;
    __doPostBack(eventTarget, eventArgument);
}
function getForm() {
    var thisForm = document.forms['form1'];
    if (!thisForm) {
        thisForm = document.form1;
    }
    if (!thisForm) {
        thisForm = document.forms['deptsearchbox'];
        if (!thisForm) {
            thisForm = document.deptsearchbox;
        }
        if (!thisForm) {
            thisForm = document.forms['homeform'];
            if (!thisForm) {
                thisForm = document.homeform;
            }
        }
    }
    return thisForm
}

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(did) {
    flyads = document.getElementById(did);
    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");
                if (click != null) {
                    //alert(click);
                    if (click) {
                        var index = click.tostr().indexOf("http");
                        var inner = anchor.innerHTML
                        if (index) { anchor.href = click.tostr().substring(index, click.tostr().indexOf("')")); anchor.onclick = ""; anchor.innerHTML = inner };
                    }
                }
            }
        }
    }
}
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"
        }
    }
    if (j == 0) {
        document.getElementById("catdrops").style.display = "none"
    }
    else{
        document.getElementById("catdrops").style.display = "block"
    }
}
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 == "Type your keywords here...") { f.inp_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();
    $("#searchResults").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);
        updateHrefs('searchResults')
        docReady();
    });
}

function showLoading() {
    document.getElementById("searchResults").innerHTML = '<br/><img src="images/loading.gif" style="padding-left:200px">';
}

function enbolden() {

    var behavior = $find('AutoCompleteExtender1');
                   
    var target = behavior.get_completionList();
    if (behavior._currentPrefix != null){
        var prefix = behavior._currentPrefix.toLowerCase();
        var i;
        for (i = 0; i < target.childNodes.length; i++)
        {
            var sValue = target.childNodes[i].innerHTML.toLowerCase();
            if (sValue.indexOf(prefix) != -1){
                var fstr = target.childNodes[i].innerHTML.substring(0, sValue.indexOf(prefix));
                var estr = target.childNodes[i].innerHTML.substring(fstr.length + prefix.length, target.childNodes[i].innerHTML.length);
                target.childNodes[i].innerHTML = fstr + '<B>' + prefix + '</B>' + estr;
            }
        }
    }
}

function doThumb(num) {
    z = document.getElementById("mainimage")
    z.i
    document.getElementById("mainimage").setAttribute("src", document.getElementById("t" + num).getAttribute("src"));
    var thumbs = document.getElementById("thumbnails").childNodes;
    for (i = 0; i < thumbs.length; i++) {
        if (thumbs[i].id == "t" + num) {
            thumbs[i].className = "thumbs selected";
        }
        else {
            thumbs[i].className = "thumbs";
        }
    }
}


function doDetailMap() {
    // Display the map
    $("#map").css("display", "block");
    $("#overlay").css("display", "block");
    $("#overlay").css("height", $(document).height());

    map = new GMap2(document.getElementById("themap"));
    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl3D());
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode("uk");
    if (!(typeof(mapData.Places) == 'undefined')) {
       var localSearch = new GlocalSearch();
	   localSearch.setSearchCompleteCallback(null, 
		 function() {
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				var marker = new GMarker(point);
                map.addOverlay(marker);
                map.setCenter(point,parseInt(mapData.Zoom));
			}else{
				//alert("Postcode not found!");
			}
		});	
		
	localSearch.execute(mapData.Places[0]);


    }
}

function closemap(t) {
    $("#themap").html('');
    $("#directionspanel").html('');
    $("#map").css("display", "none");
    $("#overlay").css("display", "none");

}

function popup_getDirections() {

    directionsPanel = document.getElementById("directionspanel");
    directionsPanel.innerHTML = '';
    directions = new GDirections(map, directionsPanel);
    directions.load("from: " + $("#mypostcode").val() + " to: " + mapData.Places[0]);
    directionsPanel.style.display = "inline";
}
function choosemore(d) {

    cancelmore();
    var i = 0;
    var sp, cb, lb;
    var dv = document.body.appendChild(document.createElement("div"));
    dv.id = "lbmore";
    for (key in d) {
        if (!d.hasOwnProperty(key)) continue;
        sp = dv.appendChild(document.createElement("span"));
        cb = document.createElement("input");
        cb.type = 'checkbox';
        cb.id = 'cb' + i;
        cb.value = d[key];
        sp.appendChild(cb);
        lb = sp.appendChild(document.createElement("label"));
        lb.htmlFor = 'cb' + i;
        lb.innerHTML = key;
        i++;
    }
    sp = dv.appendChild(document.createElement("span"));
    sp.id = "lbmoresubmit"
    var aa = sp.appendChild(document.createElement("a"));
    aa.id = 'lbmorecanx';
    aa.innerHTML = "Cancel";
    aa.setAttribute('onclick', "cancelmore()");
    aa.onclick = function () { cancelmore(); };
    var sb = document.createElement("input");
    sb.type = "button";
    sb.value = "Go";
    sb.setAttribute('onclick', 'submitmore(' + i + ')');
    sb.onclick = function () { submitmore(i) };
    sp.appendChild(sb);
    var wHeight = $(window).height();
    var wWidth = $(window).width();
    var xOffset = $(window).scrollTop();

    var cssPosObj = {
        display: 'block',
        position: 'absolute',
        top: (wHeight / 2 - $('#' + dv.id).height() / 2) + xOffset,
        left: (wWidth / 2 - $('#' + dv.id).width() / 2),
        'z-index': 9999
    }

    $('#' + dv.id).css(cssPosObj);

}

function submitmore(n) {
    var cb;
    var kw = document.getElementById("inp_keywords");
    kw.value = '';
    for (i = 0; i < n; i++) {
        cb = document.getElementById('cb' + i);
        if (cb.checked) kw.value += cb.value;
    }
    if (!(kw.value == '')) {
        kw.value = "$multi " + kw.value;
        adprs__doPostBack('Submit1', 'search')
    } else {
        cancelmore();
    }
}
function cancelmore() {
    var dv = document.getElementById("lbmore");
    if (!(typeof (dv) == 'undefined' || dv == null)) {
        dv.parentNode.removeChild(dv);
    }
}
function deptSubmit(f) {
    if (typeof f != 'undefined' && f != null) {
        var dls = f.getElementsByTagName("select");
        var kw = document.getElementById("inp_keywords");
        var kwlist = document.getElementById("keywordlist");
        kwlist.value = '';
        if (kw.value == "Type your keywords here...") kw.value = '';
        if (typeof kw != 'undefined' && kw != null && typeof dls != 'undefined' && dls != null) {
            for (var i = 0; i < dls.length; i++) {
                if (dls[i].id.substr(0, 2) == 'dl' && dls[i].selectedIndex > 0) {
                    //kw.value += ' ' + dls[i].options[dls[i].selectedIndex].text;
                    kwlist.value += ' ' + dls[i].options[dls[i].selectedIndex].value;
                }
            }
        }
        if (kwlist.value + kw.value == '') {
            var postcode = '';
            if (!(typeof (document.getElementById("postcode")) == "undefined") && !(document.getElementById("postcode") == null)) { postcode = document.getElementById("postcode").value }
            if (postcode == '') {
                kwError();
                return false;
            }
        }
        //kw.value = document.getElementById('searchpara').innerHTML.replace("Search ","") + ' ' + kw.value;

    }
    return true;
}

function homeSubmit(f) {
    if (typeof f != 'undefined' && f != null) {
        var kw = document.getElementById("inp_keywords");
        if (kw.value == 'Type your keywords here...') kw.value = '';
        var dealerval = '';
        var dealer = document.getElementById("dealer");
        if (typeof (dealer) != 'undefined' && dealer != null) {
            if (dealer.selectedIndex > 0) dealerval = dealer.options[dealer.selectedIndex].text;
        }
        if (kw.value == '' && dealerval == '') { kwError(); return false; }
    }
    return true;
}

function rollup(n) {
    var allDivs = document.getElementsByTagName("div");
    var allDivsLen = allDivs.length;
    var newstyle = '';
    var currentDiv = ''
    var parent = ''
    var curr = document.getElementById("rollup" + n).innerHTML
    if (curr == "+") {
        newstyle = "block";
        document.getElementById("rollup" + n).className = "rollup uparrow";
        document.getElementById("rollup" + n).innerHTML = "-";
    }
    else {
        newstyle = "none";
        document.getElementById("rollup" + n).className = "rollup downarrow";
        document.getElementById("rollup" + n).innerHTML = "+";
    }

    for (var i = 0; i < allDivsLen; i++) {
        currentDiv = allDivs[i];
        if (currentDiv.className == "pl") {
            if (currentDiv.parentNode) parent = currentDiv.parentNode;
            else if (currentDiv.parentElement) parent = currentDiv.parentElement;
            else return;
            if (parent.id == "plcol" + n) currentDiv.style.display = newstyle;
        }
    }
}

function hidesection(id) {
    if ($("#" + id).css("display") == "none") {
        $("#" + id).css("display","block");
    }
    else {
        $("#" + id).css("display","none");
    }
    

}

function setAutocomplete() {
    if (jQuery.ui) {
        $("#inp_keywords").autocomplete({
            source: "wordServiceJQ.ashx",
            minLength: 2
        });
    } else {
        window.setTimeout(setAutocomplete, 100);
    }
}


function searchboxrollup(t) {
    if (!(typeof (document.getElementById("searchpanel")) == "undefined") && !(document.getElementById("searchpanel") == null)) {
        if (t.innerHTML == "Show options") {
            document.getElementById("searchpanel").style.display = "";
            t.innerHTML = "Hide options";
            t.className = "uparrow"
        }
        else {
            document.getElementById("searchpanel").style.display = "none";
            t.innerHTML = "Show options";
            t.className = "downarrow"
        }
    }
    return false;
}

function entryPoint1() {
    // entry point for search results page
    updateHrefs('searchResults')
    if (!(typeof (jQuery) == 'undefined')) {
        $(document).ready(function () { setAutocomplete(); docReady(); });
    }
    else {
        window.setTimeout(entryPoint1, 100);
    }
}

function entryPoint2() {
    // entry point for department page
    updateHrefs('flyAds')
    if (!(typeof (jQuery) == 'undefined')) {
        $(document).ready(function () {

            $("#flyAds .col2").each(function (i) {
                link = $('h3 a', this).attr('href');
                $(this).append("<span class='more'><a href='" + link + "' target='_blank'> ... (more) </a></span>");
            });
            //copy top zoom to bottom
            if ($("div.pl").first().html() != null) {

                $("#catlinks").html("See more" + $("div.pl").first().html());
                if ($("div.pl").first().next().html() != null) {
                    if ($("span.choosemore", $("div.pl").first().next()).length == 0) {
                        $("#catlinks").append($("div.pl").first().next().html());
                        if ($("div.pl").first().next().next().html() != null) {
                            if ($("span.choosemore", $("div.pl").first().next().next()).length == 0) { $("#catlinks").append($("div.pl").first().next().next().html()); }
                        }
                    }
                }
            }
            setAutocomplete()
            docReady();
         });
    }
    else {
        window.setTimeout(entryPoint2, 100);
    }
    
}

function entryPoint3() {
    // entry point for home page
    if (!(typeof (jQuery) == 'undefined')) {
        $(document).ready(function () { setAutocomplete(); });
    }
    else {
        window.setTimeout(entryPoint3, 100);
    }
}

 
