// MapsCode.js for Atkins Google Maps application
// v2.0 - refactored functions
// Initial code by
// Martin Paton - m.paton@amaze.com  
// & Ben Shearer - b.shearer@amaze.com
//////////////////////////////////////////////////

// Global declaration for the google map
var map = new Object();
var mapType = new Object();
// Global zoom constants
var STREET_LEVEL = 15;
var CITY_LEVEL = 15;
var COUNTRY_LEVEL = 4;
var CONTINENT_LEVEL = 3;
var REGION_LEVEL = 3;
var url = "/our_locations/index.aspx"
//var url = "/default.aspx";
//var url = "http://localhost:52580/Default.aspx";
// Map level
var CURRENT_LEVEL = 0;

var selectedLocation;

//Continent GeoCodes & Zooms
var EUROPE = "54.525961,15.255119";
var ASIA = "12.897489183755905,114.609375";
var USA = "33.87041555094183,-93.8671875";
var MIDDLEEAST = "19.808054128088585,75.234375";

// Method: initialize
// Used to initialize the Google Map object
function initialize() {
    if (GBrowserIsCompatible()) {
        switchStyles();
        //var map = new GMap2(document.getElementById("map_canvas"));
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(20, 0), 1);
        map.setUIToDefault();
        mapType = map.getMapTypes();
        map.setMapType(mapType[3]);
    }
}



//initialise event handlers once the DOM is ready
$(document).ready
 (function() {
 
 initialize();
     initialiseEventHandlers();
     hideLoader();
     $("input#country").autocomplete(url,{extraParams:{ t:1}, dataParseOveride:true, selectOnly:true, matchSubset:0, cacheLength:1});
     $("input#location").autocomplete(url,{dataParseOveride:true, custQuery:true, selectOnly:true, matchSubset:0, cacheLength:1});
     //$('div#primary-navigation ul li.last').att('style', 'padding-right:0px');
 });

function initialiseEventHandlers() {
    //Test Code
    //alert('Handlers Initialised');

    $("ul.level2").hide();
    $("ul.level3").hide();
    $("div#locations-details").html("");
    rolloverEvents();
    leftMenu();

    //Initialises the ajax load spinner

    //InitAjaxLoadControl();
    hideLoader();
    $("a#search").click(function() {
        Search();
    });

    $(document).keydown(function(e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

        switch (key) {
            case 13:
                // Only search if we're a descendant of the search panel (otherwise will interfere)
                if (e.target.parentNode.parentNode.className == "search-panel") {
                    $("a#search").click();
                }
                break;
        }
    });
    
    $("input#country").focus(function(){ $("input#location").val(''); cache = {}; cache.data = {};cache.length = 0; $("input#location").parent().removeClass('invalid'); });
    $("input#location").focus(function(){  cache = {}; cache.data = {};cache.length = 0;});
}

// Method - leftMenu
// Renders the left hand menu
function leftMenu(active) {
    $('div.menu-tree a.selected').removeClass('selected');
    if (active == undefined) {
        $('div.menu-tree').show(); // Prevents flickering on load
        $('div.menu-tree a').click(function(event) {

            if (this == event.target) {
                $('div.menu-tree a.selected').removeClass('selected');
                $(this).addClass('selected');

                if ($(this).parent().parent().attr('class') == 'level1') {
                    $('ul.level2').hide();
                    $('ul.level3').hide();
                    $(this).next('ul').show();
                }
                else if ($(this).parent().parent().attr('class') == 'level2' & ($(this).next('ul').length > 0)) {
                    $(this).next('ul').show();
                }
                else if ($(this).parent().parent().attr('class') == 'level2' & ($(this).next('ul').length == 0)) {
                    $('ul.level3').hide();
                }

                 $('#location-title').html('');
                 if($(this).text() !=''){
                    $('div#location-title').html('<h1>' +$(this).text()+ '</h1>');
                 }
                 hideLocations();
                zoomTo($(this).parent().parent().attr('class'), $(this).attr('id'));
            }
        });

    } //end Active Test
    else {
        $('ul.level2').hide();
        $('ul.level3').hide();

        $(active).addClass('selected');
        $('#location-title').html('');
        var act = '<h1><a>' + $(active).text() + '</a></h1>';
        
            $('div#location-title').html(act);
            
        
        var activeClass = active.parent().parent().attr('class');
        var activeClassP = active.parent().attr('class');
        if (activeClass == 'level1') {
            $('ul.level2').hide();
            $('ul.level3').hide();
            active.next('ul').show();
        }
        else if (activeClass == 'level2' & (active.next('ul').length > 0)) {
            active.parent().parent().show();
            active.next('ul').show();
        }
        else if (activeClass == 'level2' & (active.next('ul').length == 0)) {
            $('ul.level3').hide();
            active.parent().parent().show();

        }
        else if (activeClass == 'level3' & (active.next('ul').length == 0)) {
            $('ul.level3').hide();
            active.parent().parent().show();
            active.parent().parent().parent().show();
            active.parent().parent().parent().parent().show();

        }

    }


}

//Method
//Binds the drop down list rollover events to handle the IE issue
function rolloverEvents() {

    $('div.menu-tree a').bind('mouseover', function(event) {
        //Add 'hover' class on rollover
        $(this).addClass('hover');
    })
        .bind('mouseout', function(event) {
            //Add 'hover' class on rollover
            $(this).removeClass('hover');
        })
}

function bindHoverStates(item) {

    $(item).bind('mouseover', function(event) {
        //Add 'hover' class on rollover
        $(this).addClass('Hover');
        //alert($(this).attr('class'));
    })
        .bind('mouseout', function(event) {
            //Add 'hover' class on rollover
            $(this).removeClass('Hover');
        })

}


// Method: bindEvents
// Used to rebind the onclick functions after an AJAX post
var bindEvents = function() {
    $(".output_location a").click(function() {
        var selected = $(this).text();
        $("input#location").val(selected);
        $(".output_location").hide();
    });

    $(".output_country a").click(function() {
        var selected = $(this).text();
        $("input#country").val(selected);
        $(".output_country").hide();
    });
}

// Event handler - rebinds click events after non-ajaxian functions (purely for brevity)
var bindNonAjax = function() {
    $("a.click-to-show").click(function() {
        //showLocation($(this).parent().children("input.geocode").attr('text'), "<h2>" + $(this).parents("div.location-block").children("h2").html() + "</h2>" + $(this).parent().children("address").html(), "", STREET_LEVEL);
        showLocation($(this).parent().children("input.geocode").attr('text'),"<h2>" + $(this).parents("div.location-block").children("h2").html() + "</h2>" + $(this).parent().children("address").html(),"",STREET_LEVEL, $(this).parent().children("div.contact-block"))
    });



}


function Hide(elm) {
    $("div.output_country").hide();
    return false;
}


function Search() {

    //alert('search');
    var $inputLocation = $("input#location").val();
    var $inputCountry = $("input#country").val();
    
	var reg = /^[a-z|\u00D3\u00E4\u00e5]{0,49}$/i;
		
	var locValid = reg.test($inputLocation);
	var counValid = reg.test($inputCountry);
    
    // Basic error handling
    if ($inputLocation == '' && $inputCountry == '') {
        //alert("Please enter a search parameter");
        $('div.search-panel').addClass('no-param');
    }
//    else if((!locValid || !counValid) && ()){
//        
//        $('div.search-panel').addClass('invalid');
//        
//    }
    else if ($inputLocation == '' && $inputCountry != '' && counValid) {
        //leftMenu($('div.menu-tree a#' + translate($inputCountry.toLowerCase())));
        $('div.search-panel').removeClass('invalid');
        zoomTo("country", $inputCountry);
    }

    else if ($inputLocation != '' && $inputCountry == '' && locValid) {
        //leftMenu($('div.menu-tree a#' + translate($inputLocation)));
        zoomTo("location", $inputLocation);

    }

    else if(locValid && counValid) {
        leftMenu($('div.menu-tree a#' + $inputLocation.toLowerCase()));
        zoomTo("CountryLocation", $inputCountry + ';' + $inputLocation);
    }
}



// Method: zoomTo
// params: level - the level of the node
// params: id - the destination
function zoomTo(level, id) {
    // Wick off the div.our-locations   

    $("div.locations-intro").hide();

    if (level == 'level1') {
        var destination = new Array();

        if (id.indexOf('-&-') > -1) {
            do {
                id = id.replace('-&-', '-%26-');

            } while (id.indexOf('-&-') != -1)
        }
        else if (id == 'usa') {
            //id = 'north-america';
            id='usa'
        }
        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url: url + "?t=7&q=" + id,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id);
                bindEvents();
                bindNonAjax();
                hideLoader();
                bindtitle(msg);
            }

        });
        // showLocation(destination, null, null, CONTINENT_LEVEL);
        //hideLocations();
    }
    else if (level == 'level2') {

        if (id.indexOf('---') == -1 & id.indexOf('-') != -1) {
            do {
                id = id.replace('-', ' ');
            }
            while (id.indexOf('-') != -1)

        }
        else {
            id = id.replace('---', '|||');
            do {
                id = id.replace('-', ' ');
            }
            while (id.indexOf('-') != -1)

            id = id.replace('|||', ' - ');


        }

        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url:url + "?t=5&q=" + id,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id);
                bindEvents();
                bindNonAjax();
                hideLoader();
                bindtitle(msg);
            }

        });

    }

    else if (level == 'level3') {

        do {
            id = id.replace('-', ' ');
        }
        while (id.indexOf('-') != -1)

        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url: url + "?t=4&q=" + id,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id); bindEvents(); bindNonAjax();bindtitle(msg);
                hideLoader();
            }

        });
    }

    else if (level == 'location') {
	   
        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url: url + "?t=6&q=" + encodeURI(id),
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id); openTree(msg); bindEvents(); bindNonAjax();bindtitle(msg);
                hideLoader();
            }

        });
    }

    else if (level == 'country') {

        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url: url + "?t=5&q=" + id,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id); openTree(msg); bindEvents(); bindNonAjax();bindtitle(msg); 
                hideLoader();
            }

        });
    }
    else if(level == 'CountryLocation'){
        $.ajax({
            type: "POST",
            beforeSend: function() { showLoader(); },
            url: url+ "?t=8&q=" + id,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                parseJson(msg, id); openTree(msg); bindEvents(); bindNonAjax();bindtitle(msg);
                hideLoader();
            }

        });
    }
}

//Method to transform JSON Object
function parseJson(data, what) {

    renderOffices(data, what);
    showAll();
}


var selectedLoc;

function bindtitle(data){
    if(data.root != null){
        if ( data.root.weblink != null && data.root.weblink.length > 0) {
             var title = $("#locations div#location-title").text();
             $("#locations div#location-title").html("<h1>" + title + "  - <a href=\"" + data.root.weblink + "\">" + data.root.weblink.substring(7) + "</a></h1>").show();
        }
    }

}

function openTree(data) {
    var location;

    if(data.root != null){
        if ( data.root.location.length != null && data.root.location.length > 0) {
            location = data.root.location[0];
        }
        else {
            location = data.root.location;
        }
    


        if (location.region == undefined) {
            //alert(data.root.location[0].office.address.country);

            leftMenu($('div.menu-tree a#' + unTranslate(location.office.address.country)));
            
            
        }
        else if (location.region != undefined) {
            //alert(location.region);
            leftMenu($('div.menu-tree a#' + unTranslate(location.region)));
            
        }
    }

}
//Method : replaceSpaces
//Params : input - string to be altered; 
//Returns : String
//Replaces spaces with dashes in ID selection strings
function replaceSpaces(input) {
    var retString = input;
    do {
        retString = retString.replace(' ', '-');
    }
    while (retString.indexOf(' ') > -1)

    return retString;
}

// Method: renderOffices
// params: msg - the JSON serialized data to render

function renderOffices(msg, id) {
    // Writes the offices into the #location div
    if (msg != 'undefined' && msg != null && msg != '') {
        var output = "";
        output = writeLocations(msg.root, id);
    }
    $("#locations-details").innerHTML = output;
}


/* Returns a <div> of a single office data */
function writeLocations(data, id) {
	
    try {
        var output = "";

        if (typeof (data.location.length) != 'undefined') {
            //output += "<h1>" + translate(id) + "</h1>";
            //output += "<h1>" + data.location[0].office.address.country + "</h1>";
            
//            var menuItemID = unTranslate(id.toLowerCase())
//            if(menuItemID != 'middle-east-&-india'){
//                var t=$('div.menu-tree a#'+ menuItemID);
//                var headingText = t.text();
//                
//                if(headingText == '')
//                {
//                   if(data.location[0].office.address.country != 'United Kingdom'){
//                    headingText = data.location[0].office.address.country;
//                    }
//                    else{
//                        headingText = 'UK'
//                    }
//                
//                }
//             
//                output += "<h1>" + headingText + "</h1>";
//            }
//            else{
//                output += "<h1>Middle East &amp; India</h1>";
//            }
            // we have multiple locations in this country
            for (var i = 0; i < data.location.length; i++) {
                //Float the object Left or right in the top level div
                if (((i + 1) % 2) == 1) {
                    output += "<div class=\"location-block lft\">";
                }
                else {
                    output += "<div class=\"location-block rgt\">";
                }
                output += "<h2>" + data.location[i].name + "</h2>";
                output += writeOffices(data.location[i]);
                output += "</div>";
            }
        }
        else { // We only have one to deal with
            //output += "<h1>" + data.location.office.address.country + "</h1>";
            
//            var menuItemID = unTranslate(id.toLowerCase())
//            if(menuItemID != 'middle-east-&-india'){
//                var t=$('div.menu-tree a#'+ menuItemID);
//                var headingText = t.text();
//                
//                if(headingText == '')
//                {
//                   if(data.location.office.address.country != 'United Kingdom'){
//                    headingText = data.location.office.address.country;
//                    }
//                    else{
//                        headingText = 'UK'
//                    }
//                
//                }
//             
//                output += "<h1>" + headingText + "</h1>";
//            }
//            else{
//                output += "<h1>Middle East &amp; India</h1>";
//            }
//            
            
            output += "<div class=\"location-block\">";
            output += "<h2>" + data.location.name + "</h2>";
				    
            output += writeOffices(data.location);

            output += "</div>";
        }


        $("div#locations-details").html(output).show();
        bindEvents();
    }
    catch (e) {
        var searchTerms;
        
        if($('input#country').val() == '' || $('input#location').val() == '' ){
        
            searchTerms = $('input#country').val() + $('input#location').val();
        }
        else{
            searchTerms = $('input#country').val() + ' &amp; ' + $('input#location').val();
        }
        $("#locations div#location-title").html('');
        $("#locations div#location-title").html("<h2>No locations found to match '" + searchTerms + "' please try again.</h2>").show();
        hideLocations();
        hideLoader();
    }
}

function writeOffices(data) {
    try {
        var output = "<div class=\"office-block\">";
        if (typeof (data.office.length) != 'undefined') { // Check for < 1 office at this location (should never happen)
            for (var i = 0; i < data.office.length; i++) {
                output += writeAddress(data.office[i]); // Process a collection of offices
            }
        }
        else {
            output += writeAddress(data.office); // Only one office, so process the object directly
        }

        output += "</div>"
        //alert("After offices: " + output);


        return output;
    }
    catch (e) { }
}

function writeAddress(office) {
    try {
        var output = "<div class=\"address-block\">"; // Define output string
        output += "<a href=\"#\" class=\"click-to-show\">Detailed View</a>";
        output += "<input class=\"geocode\" type=\"hidden\" text=\"" + office.geocode + "\">";
        output += "<address>";
        output += normaliseStringWithBreak(office.address.address1) + normaliseStringWithBreak(office.address.address2) + normaliseStringWithBreak(office.address.address3);
        output += normaliseStringWithBreak(office.address.town) + normaliseStringWithBreak(office.address.postcode) + normaliseStringWithBreak(office.address.country);
        output += "</address>";

        // Do the contacts for each office.

        if (!isNaN(office.contact.length) || office.contact == null || office.contact == 'undefined') {
            for (var i = 0; i < office.contact.length; i++) {
                output += writeContact(office.contact[i]);
            }
        }
        else {
            output += writeContact(office.contact);
        }
        //  alert("After addresses: " + output);
        return output + "</div>"
    }
    catch (e) { }
}

/* Writes the contact part of the information */
function writeContact(office) {
    try {
        var output = "";
        output += "<div class=\"contact-block\">";
        if(office.contact_type != 'Atkins')
        {
            output += "<p><strong id=\"contact-type\">" + normaliseString(office.contact_type) + "</strong></p>";
        }
        else
        {
            output += "<p><strong style=\"display:none\" id=\"contact-type\">" + normaliseString(office.contact_type) + "</strong></p>";
        }
        //output += "<p>Contact name: <strong>" + normaliseString(office.name) + "</strong>" + "</p>";
	
	var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
	var locValid = reg.test(normaliseString(office.email));
	if (locValid)
	{
        output += "<p>Contact: <strong><a href=\"mailto:" + normaliseString(office.email) + "\">" + normaliseString(office.email) + "</a></strong></p>"
        }
	else
	{
        output += "<p>Contact: <strong>" + normaliseString(office.email) + "</strong></p>"
        }
	//output += "<p>Office email: <strong><a href=\"mailto:" + normaliseString(office.office_email) + "\">" + normaliseString(office.office_email) + "</a></strong></p>"    
        output += "<p>Tel: <strong>" + normaliseString(office.tel) + "</strong></p>"
        if(normaliseString(office.fax) != "")
{
        output += "<p>Fax: <strong>" + normaliseString(office.fax) + "</strong></p>"
}
        output += "</div>";

        //  alert("At contact: " + output);
        return output;
    }
    catch (e) { }
}

/* Normalises a string without breaks - if empty, returns nothing */
function normaliseString(input) {
    try {
        if (input == "" || input == "null" || input == "undefined" || input == null) { return ""; }
        else { return input; }
    }
    catch (e) { }
}

/* Normalises a string with breaks - if empty, returns nothing */
function normaliseStringWithBreak(input) {
    try {
        if (input == "" || input == "null" || input == "undefined" || input == null) { return ""; }
        else { return input + "<br />" }
    }
    catch (e) { }
}

// This function shows a block of Geocodes on the map at country level after the data has been retrieved.
function showAll() {

    map.clearOverlays();
    var showLinks = $("a.click-to-show");
    var latGeoCode = new Array();
    var lonGeoCode = new Array();
    showLinks.each(function() {
        showLocation($(this).parent().children("input.geocode").attr('text'), "<h2>" + $(this).parents("div.location-block").children("h2").html() + "</h2>" + $(this).parent().children("address").html(), "", COUNTRY_LEVEL, $(this).parent().children("div.contact-block"));
        var code = $(this).parent().children("input.geocode").attr('text');

        latGeoCode.push(parseFloat(code.split(',')[0]));
        lonGeoCode.push(parseFloat(code.split(',')[1]));

    });

    centerAndZoomMap(latGeoCode, lonGeoCode);

    
}

function centerAndZoomMap(lat, lon) {
    //alert("center & Zoom");
    if(lat.length > 0 && lon.length > 0){
    lat.sort(function(a, b) { return a - b });
    lon.sort(function(a, b) { return a - b });
    var swC = new GLatLng(lat[0], lon[0], false);
    var neC = new GLatLng(lat[lat.length - 1], lon[lon.length - 1], false)
    var bounds = new GLatLngBounds(swC, neC);
    var fullLng = bounds.isFullLat();
    var fullLat = bounds.isFullLng();
    if (fullLat == true) {
        alert('Full Longitutde!! SWLat: ' + swC.lat() + 'SWLong: ' + swC.Lng() + 'NE Lat: ' + neC.lat() + ' NE Long: ' + neC.lng());
    }
    var zLevel = map.getBoundsZoomLevel(bounds) - 1;
    if (zLevel > 12) {
        zLevel = 12;
        map.setMapType(mapType[0]);
    }
    else {
        map.setMapType(mapType[0]);
    }
    var center = bounds.getCenter();
    map.setCenter(center, zLevel);
    }
    else{
        map.setCenter(new GLatLng(20, 0), 1); 
        map.setMapType(mapType[3]);
        $('ul.level2').hide();
        $('ul.level3').hide();
    }

}

function showLocation(geocode, data, shared, level, contacts) {

    // This function takes HTML data for an office address, the geocode, and the data to show in the window.
    // If the office is shared, the F+G logo is displayed.

    // Set up the icon

    var tinyIcon = new GIcon();
    
    tinyIcon.image = "/images/blue-dot.png";
    tinyIcon.iconSize = new GSize(32, 32);
    tinyIcon.shadowSize = new GSize(31, 30);
    tinyIcon.iconAnchor = new GPoint(16, 30);
    tinyIcon.infoWindowAnchor = new GPoint(25, 1);
    var markerOptions = { icon: tinyIcon };

    // Get the co-ordinates

    var lat = geocode.split(",")[0];
    var lon = geocode.split(",")[1];

    var infoWindowHTML = data;

    var marker = new GMarker(new GLatLng(lat, lon), markerOptions);
    //var marker = new GMarker(new GLatLng(lat, lon));
    if (level != CONTINENT_LEVEL) {
        map.addOverlay(marker);
    }
    map.setCenter(new GLatLng(lat, lon), level);
    // Get the map on.

    GEvent.addListener(marker, "click", function() {
        var infoOptions = new Object();
        infoOptions.pixelOffset = new GSize(10, 10)

        //marker.openInfoWindowHtml(infoWindowHTML);
        if (contacts != null) {
            var tabs = new Array();
            tabs[0] = new GInfoWindowTab('Address', data);
            for (var i = 0; i < contacts.length; i++) {
                var cHTML = "<div style=\"display:block; width:" + (contacts.length + 1) * 100 + "px\">" + $(contacts[i]).html() + "</div>";
                var cType = $(contacts[i]).children('p').children('#contact-type').text();
                if(cType == 'Faithful+Gould'){cType = 'F+G';}
                tabs[i + 1] = new GInfoWindowTab(cType, cHTML);
            }
            // marker.openInfoWindowTabsHtml(tabs,  {pixelOffset:new GSize(10,10)} );
            marker.openInfoWindowTabsHtml(tabs);
        }
    });
}

//Ajax Loader control

function showLoader() {
    $('#loader').addClass('loader_active');
    //$('#loader').attr('style', 'height:' + $('#loader').next().height() + 'px;' + 'width:' + ($('#loader').next().width()) + 'px;');
}
function hideLoader() {
    $('#loader').removeClass('loader_active');
}


function hideLocations() {
    var locationsDiv = $('div#locations-details');
    locationsDiv.html('');
}

function translate(id) {
    if (id.indexOf('-') > -1) {
        do {
            id = id.replace('-', ' ');
        }
        while (id.indexOf('-') != -1)

    }

    if (id.indexOf('%26') > -1) {

        do {
            id = id.replace('%26', '&');
        }
        while (id.indexOf('%26') > -1)
    }
    return id.toLowerCase();
}
function unTranslate(id) {
    if (id.indexOf(' ') > -1) {
        do {
            id = id.replace(' ', '-');
        }
        while (id.indexOf(' ') != -1)

    }

    if (id.indexOf("%26") > -1) {

        do {
            id = id.replace("%26", "&");
        }
        while (id.indexOf("%26") > -1)
    }
    return id.toLowerCase();
}


//Custom Data Parser for jQuery.AutoComplete
function customDataParser(data){

    //var retArray = new Array();
    
    var jOb = eval('('+data+')');
    
    var retArr = new Array();
    var row;
    for(var i = 0; i < jOb.data.list.length; i++)
    {
        // PCD Added
        row = $.trim(jOb.data.list[i]);
        if(row)
        {
            retArr[retArr.length] = [row,row];
        }
        // PCD End
    }
    
    return retArr ;
}
function customQuery(value){
    
    var country = $('input#country').val();
    if (hasVal(country)) {
    
        return "?q=" + country  +";" + value + "&t=3";
    }
    else{
        
       return "?q=" + value + "&t=2";
    }
}


function hasVal(value)
{
    if (value.length > 0 && value != "" && value != 'undefined' && value != null) {
        return true;
    
    }
    else {return false;}
}
function switchStyles()
{
    //alert('switchStyles');
    var title = "safari";
  	var apple = "Apple";

            try{
	  if (navigator.vendor.indexOf(apple) >-1 )
	  {
		 //alert("true");
			setActiveStyleSheet(title);
	  }
                }
          catch(error){}

	
}