﻿function doPostBackAsync(eventName, eventArgs) {
    eventName = 'inputHDN';
    eventArgs = 'onclick';

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
        prm._asyncPostBackControlIDs.push(eventName);
    }

    if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
        prm._asyncPostBackControlClientIDs.push(eventName);
    }

    __doPostBack(eventName, eventArgs);
}

//function localMousedownHandler(e) {
//    if (window.event)
//        window.event.cancelBubble = true;
//    else
//        e.stopPropagation();
//    return false;
//}

var isIE = IE();

function IE() {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        return true;
    else
        return false;
}

function EnableTopSearch() {

    var menuz = document.getElementById('menuz');
    menuz.style.zIndex = 1;
    var topSearch = document.getElementById('topsearch');
    topSearch.style.zIndex = 2;
  //  alert('enable');
    if (IE()) {
        //        topSearch.style.position = "";
        //        topSearch.style.height = "";
        //        topSearch.className = "topsearchabs";
        //        topSearch.style.margin = "0px 0px 25px";
        var newWidth = "885px";

        // for IE, screen resolution  1280x768, 1280x1024
        if (document.body.clientWidth == 1252)
            var newWidth = '800px';
        // for IE, screen resolution  1024x768
        if (document.body.clientWidth <= 1024)
            var newWidth = '673px';
        topSearch.style.left = newWidth;
    }
//        if (isIE) {
//            var kids = topSearch.childNodes;
//            for (j = 0; j < kids.length; j++) {
//                if (kids[j].tagName != "SCRIPT") {
//                    kids[j].style.height = "300px";
//                    var kidsch = kids[j].childNodes;
//                    for (i = 0; i < kidsch.length; i++) {
//                        if (kidsch[i].tagName != "SCRIPT") {
//                            kidsch[i].style.height = "300px";
//                        }
//                    }
//                }
//            }
//        }       

//    }
//    else {
//        topSearch.style.height = "300px";
//    }
}

function DisableTopSearch() {
   // alert('disable');
    var menuz = document.getElementById('menuz');
    menuz.style.zIndex = 2;
    var topSearch = document.getElementById('topsearch');
    topSearch.style.zIndex = 1;
    
//    if (IE()) {
//        topSearch.style.position = "absolute";
//            topSearch.className = "";            
//        }
//        topSearch.style.height = "22px";
//        if (isIE) {        
//            var kids = topSearch.childNodes;
//            for (j = 0; j < kids.length; j++) {
//                if (kids[j].tagName != "SCRIPT") {
//                    kids[j].style.height = "22px";
//                    var kidsch = kids[j].childNodes;
//                    for (i = 0; i < kidsch.length; i++) {
//                        if (kidsch[i].tagName != "SCRIPT") {
//                            kidsch[i].style.height = "22px";
//                        } 
//                    }
//                }
//            }
//        }       
}

function check(browseFile) {
    var ext = browseFile.value;    
    ext = ext.substring(ext.length - 3, ext.length);
    ext = ext.toLowerCase();
    if (ext != 'jpg' && ext != 'gif') {
        alert('You selected a .' + ext + ' file; please select a .jpg or .gif file instead!');
        return false;
    }
    else
        return true;
}

var selOptA = 0;
var selOptB = 0;
function checkOpts() {
    if (selOptA > 0 && selOptB > 0) {
        var thisSubmit = document.getElementById('thisSubmit');
        if (thisSubmit != null) {
            thisSubmit.value = 'Click here to continue!';
            thisSubmit.disabled = false;
        }
    }
}


var thisLoginLink = '<a href="javascript:toggleBox(\'msloginbox\');" style="text-decoration:none; font-weight:bold; color:#acff51;"><img src="/_common/img/web/act.gif" width="143" height="16"></a><br><div id="msloginbox" style="display:none;"><div id="logincontent"><form style="background-color:#ffc20f;"><b>E-mail Address:</b><br><input type="text" name="tryEmail" style="width:180px;color:#b1ae9e;" id="tryEmail" value="FOR ALL OPTIONS" onFocus="$(\'tryEmail\').value=\'\';"><br>&nbsp;<br><b>Password:</b><br>New users: create your own password.<br>(6-20 chars, a-z,0-9)<br><input type="text" style="width:180px;color:#b1ae9e;" id="passNote" value="FOR EXISTING AND NEW ACCOUNTS" onFocus="Element.hide(\'passNote\');Element.show(\'tryPass\');$(\'tryPass\').focus();"><input type="password" name="tryPassword" style="width:180px;color:#b1ae9e;display:none" id="tryPass"><br>&nbsp;<br><b>I want to:</b><br><center><input type="button" value="Log In To Existing Account" onClick="tryLogin()" style="width:150px"><br><input type="button" value="Register New Account" onClick="tryRegister()" style="width:150px"><br><input type="button" value="Find my password" onClick="tryGetPass()" style="width:150px"></center></form><a href="/web/users/">Find out more about myShortcuts</a></div><img src="/web/users/loginbgend.gif"></div>';

var currentDef = null;
function swap(target) {
    if (document.getElementById) {
        obj = document.getElementById(target);
        if (obj.style.display == "none") {
            obj.style.display = "";
        }
        if ((currentDef != null) && (obj != currentDef)) {
            currentDef.style.display = "none";
        }
        currentDef = obj;
    }
}

function toggleBox(target) {
    if (document.getElementById) {
        obj = document.getElementById(target);
        if (obj.style.display == "none") {
            obj.style.display = "";
        } else {
            obj.style.display = "none";
        }
    }
}

function Recaptcha() {
    var capthcaImg = document.getElementById("imgCaptcha");
    var newSrc;
    capthcaImg.src = capthcaImg.src + "&" + (new Date()).getTime().toString();
    newSrc = capthcaImg.src;
    return false;
}

function load() {
    var topSearch = document.getElementById('topsearch');
    var newWidth = "885px";

    // for IE, screen resolution  1280x768, 1280x1024
    if (document.body.clientWidth == 1252)
        var newWidth = '800px';
    // for IE, screen resolution  1024x768
    
    if (document.body.clientWidth <= 1024)
        var newWidth = '673px';
    topSearch.style.left = newWidth;
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    GetMap();
}

function EndRequestHandler(sender, args) {
    GetMap();
}

function RemoveCookie(cookieName, cookieValue) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1000);
    document.cookie = cookieName + '=' + cookieValue + '; path=/;' + 'expires=' + exp.toGMTString();
}

function SetCookiePostBackAsync(cookies) {//cookieName, cookieValue) {
    for (i = 0; i < arguments.length; i = i + 2) {
        document.cookie = arguments[i] + '=' + arguments[i + 1] + '; path=/;';
    }
    //document.cookie = cookieName + '=' + cookieValue + '; path=/;';
    //closing popup
    var sc = document.getElementById('mapContainer');
    if (sc != null) {
        VEHideVEShapeERO(false);
    }
    doPostBackAsync();
}

function RedirectPageCookie(cookieName, cookieValue, page) {
    //var exp = new Date();
    //exp.setTime(exp.getTime() + 1000*5);
    document.cookie = cookieName + "=" + cookieValue + "; path=/";
    //localStorage.setItem(cookieName, cookieValue);
    //+ expires=" + exp.toGMTString();
    //alert(document.cookie);
    window.location = page;
}
function OnPluginErrorHandler(sender, errorArgs) {
    var errorMsg = "Silverlight Plugin Error: \n\n";
    //alert('error occured');
}

function getCookie(name, remove) {
    var prefix = name + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1) return null;
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
    var value = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
    if (remove)
        RemoveCookie(name, value);
    return value;
}

//function loadcontrol() {
//    var sc = document.getElementById('loadspeccatcontrol');
//    sc.value = "true";
//    var form = document.forms['aspnetForm'];
//    form.submit();
//}

var map = null;
var mapitem = '';
var LA = null;

function GetMap() {
    mapitem = '';
    var sc = document.getElementById('mapContainer');
    if (sc != null) {
        LA = new VELatLong(-33.995, 18.655);
        map = new VEMap('mapContainer');
        map.LoadMap(LA, 10, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 1);
        getAllItemsLocation();
        getItemLocation();
        return;
    }
    //map with town information
    var mct = document.getElementById('divMapTowns');
    if (mct != null) {
        getAllItemsLocation();
        getTownDescription();
        LA = new VELatLong(-33.995, 18.655);
        map = new VEMap('divMapTowns');
        map.HideDashboard();
        map.LoadMap(LA, 10, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 1);
        map.Resize(582, 380);
        map.AttachEvent('onendzoom', function(obj) { zoomControl(map); });
        map.AttachEvent('onmousewheel', EventMouseWheel);
        return;
    }
    var mp = document.getElementById('divMapProvince');
    if (mp != null) {
        getProvinceLocation();
        return;
    }

}

function EventMouseWheel() {
    //insert custom behavior here...
    //return true to disable the default behavior. return false to enable the default behavior.
    return true;
}

zoomMax = 15;
zoomMin = 0;

function zoomControl(obj) {
    var currentZoom = obj.GetZoomLevel();

    if (currentZoom > zoomMax) {
        map.SetZoomLevel(zoomMax);
    } else if (currentZoom < zoomMin) {
        map.SetZoomLevel(zoomMin);
    }
}


function getTownDescription() {
    CapeTown4uService.GetTownDescription(
                                     GetTownDescription_success, GetTownDescription_onFailed, '');
}

function GetTownDescription_success(e) {
    var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
    var divTownShortDescription = document.getElementById('divTownShortDescription');
    if (result.ShortDescription != "") {
        divTownShortDescription.innerHTML = result.ShortDescription +
                " - <a href='javascript:void(0);' onclick=\"SetCookiePostBackAsync('DescriptionTownID','" + getCookie('TownID', false) + "');\">Read more</a>";
    }
    else
        divTownShortDescription.innerHTML =
                "<a href='javascript:void(0);' onclick=\"SetCookiePostBackAsync('DescriptionTownID','" + getCookie('TownID', false) + "');\">Read more</a>";
    if (result.Categories != "") {
        var divTownCategories = document.getElementById('divTownCategories');
        divTownCategories.innerHTML = result.Section + " In " + result.Name + ".<br/>" +
                result.Section + " categories available in " + result.Name + " include " +
                result.Categories + ". View " + result.Name + " " + result.Section +
                " adverts listed on CapeTown4u.co.za by clicking on selected " +
                result.Section + " links in the right-hand column of this page.";
    }
    RemoveCookie('TownID', '1');
    //var LA = new VELatLong(-33.995, 18.655);

    //            myPolygon.SetTitle("My Polygon");
    //            myPolygon.SetDescription("This is the description for my polygon.");
}

function GetTownDescription_onFailed() {
    alert("Error in CapeTown4uService.GetTownDescription");
}


function getItemLocation() {
    CapeTown4uService.GetItemLatLong(
                                     GetItemLatLong_success, GetItemLatLong_onFailed, '');
}
function GetItemLatLong_success(e) {
    var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
    if ((result.Latitude != 0) && (result.Longitude != 0)) {
        var itemLocation = new VELatLong(result.Latitude, result.Longitude);
        var itemShape = new VEShape(VEShapeType.Pushpin, itemLocation);
        itemShape.SetTitle("<div><img src='App_Themes/Default/Images/" + result.ImagePath + "'  height='100'/></div>"
                + "<a href='javascript:void(0);' onclick=\"SetCookiePostBackAsync('ItemID',' " + result.ItemID + "');\" style='text-decoration:underline;'>" + result.ItemName + "</a><br><br>Latitude: " + result.Latitude + "<br>Longitude: " + result.Longitude);
        mapitem = result.ItemName;

        itemShape.SetCustomIcon("<img src=\'App_Themes/Default/Images/mapitemselected.gif\'/>");
        map.AddShape(itemShape);
        var exp = new Date();
        exp.setTime(exp.getTime() - 1000 * 5);
        document.cookie = "MapItemID=;expires=" + exp.toGMTString();
        var points = new Array();
        points[0] = itemLocation;
        map.SetMapView(points);
        map.SetZoomLevel(12);
    }
    //getAllItemsLocation();
    //                else {
    //                    alert("Location is not defined for this item.");
    //                }

}

function GetItemLatLong_onFailed() {
    alert("Error in CapeTown4uService.GetItemLatLong");
}

function getProvinceLocation() {
    CapeTown4uService.GetProvinceLocation(
                                     GetProvinceLocation_success, GetProvinceLocation_onFailed, '');
}


function GetProvinceLocation_success(e) {
    var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
    var zoom = 10;
    if ((result.Latitude != 0) && (result.Longitude != 0)) {
        LA = new VELatLong(result.Latitude, result.Longitude);
        zoom = result.Zoom;
    }
    else
        LA = new VELatLong(-33.995, 18.655);
    map = new VEMap('divMapProvince');
    map.HideDashboard();
    map.LoadMap(LA, zoom, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 1);
    map.Resize(582, 380);
    map.AttachEvent('onendzoom', function(obj) { zoomControl(obj); });
    map.AttachEvent('onmousewheel', EventMouseWheel);

}

function GetProvinceLocation_onFailed() {
    alert("Error in CapeTown4uService.GetProvinceLocation");
}


function getAllItemsLocation() {
    CapeTown4uService.GetAllItemsLatLong(
                                     GetAllItemsLatLong_success, GetAllItemsLatLong_onFailed, '');
}

function GetAllItemsLatLong_success(e) {
    if (e == "") return false;
    var result = Sys.Serialization.JavaScriptSerializer.deserialize(e, true);
    if (result.length > 0) {
        for (var i = 0; i < result.length; i++) {
            var item = result[i];
            if ((item.Latitude != 0) && (item.Longitude != 0) && (item.ItemName != mapitem)) {
                var itemLocation = new VELatLong(item.Latitude, item.Longitude);
                var itemShape = new VEShape(VEShapeType.Pushpin, itemLocation);
                itemShape.SetTitle("<div><img src='App_Themes/Default/Images/" + item.ImagePath + "'  height='100'/></div>"
                        + "<a href='javascript:void(0);' onclick=\"SetCookiePostBackAsync('ItemID',' " + item.ItemID + "');\" style='text-decoration:underline;'>" + item.ItemName + "</a><br><br>Latitude: " + item.Latitude + "<br>Longitude: " + item.Longitude);
                itemShape.SetCustomIcon("<img src=\'App_Themes/Default/Images/mapitem.gif\'");
                //itemShape.SetMinZoomLevel(8);
                map.AddShape(itemShape);
            }
        }
        var points = new Array();
        for (var i = 0; i < result.length; i++) {
            var point = new VELatLong(result[i].Latitude, result[i].Longitude);
            points[i] = point;
        }
        map.SetMapView(points);
    }
}

function GetAllItemsLatLong_onFailed() {
    //alert("Error in CapeTown4uService.GetAllItemsLatLong");
}


function getInfo() {
    var info;
    var center = map.GetCenter();

    info = "Zoom level:\t" + map.GetZoomLevel() + "\n";
    info += "Latitude:\t" + center.Latitude + "\n";
    info += "Longitude:\t" + center.Longitude;
    map.ShowAllShapeLayers();
    alert(info);
}
