var geocoder = null;

String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}

$(function () {

    var exisingBaseUrl = $("#baseId").attr("href");
    if (window.location.hostname.indexOf("www.") == -1) {
        exisingBaseUrl = exisingBaseUrl.replace("www.", "");
    }

    $("#baseId").attr("href", exisingBaseUrl);

    google.maps.Map.prototype.markers = new Array();

    google.maps.Map.prototype.addMarker = function (marker) {
        this.markers[this.markers.length] = marker;
    };

    google.maps.Map.prototype.getMarkers = function () {
        return this.markers
    };

    google.maps.Map.prototype.clearMarkers = function () {
        for (var i = 0; i < this.markers.length; i++) {
            this.markers[i].setMap(null);
        }
        this.markers = new Array();
    };

    $.ajax({ url: "ajax/template_list.aspx", cache: true, success: onGetTemplatesResponse });


    $("#letterPanel a").corner("top 3px");
    $("#locationPanel").corner("left 5px");
    $("#mainMenu li").corner("top 5px");
    $(".loginTab").corner("bottom 5px");

    $("#letterPanel a").mouseenter(function () {
        showMenuCategory($.trim($(this).text()));
    });

    $("#categoryPanel").mouseenter(function () {
        showMenuCategory(null);
    });

    $("#letterPanel a").mouseleave(function () {
        hideMenuCategory();
    });

    $("#categoryPanel").mouseleave(function () {
        hideMenuCategory();
    });
    $(".controls").each(function () {

        $(this).prepend(' <a href="javascript:void(0);" class="manageRecord" title="manage"><img src="images/edit.gif" alt="manage listing" /></a>');
        $(this).prepend('<a href="javascript:void(0);" class="deleteRecord" title="delete"><img src="images/delete.gif" alt="delete listing" /></a>');

    });
    $(".deleteRecord").click(function () {
        var businessId = $(this).parent().parent().attr("id").split("_")[1];
        showDeleteDialog(businessId);
    });
    $(".manageRecord").click(function () {
        var businessId = $(this).parent().parent().attr("id").split("_")[1];
        showManageDialog(businessId);
    });
    $("#locationPanel a").click(function () {
        $.blockUI({ message: '<h1>Loading...</h1>', fadeIn: 0 });
        var url = $(this).attr("href");
        var county = url.split("/")[1].split(".")[0];
        


        if (url.split("/").length == 2) {
            url = "ajax/business_listbyarea.aspx?area=" + county;
           // history.pushState({}, county, "counties/" + county + ".aspx");

            $.ajax({ url: url,
                success: function (response) {
                    var areaSection = $("#locationPanel");
                    areaSection.html("");
                    for (var i = 0; i < response.areas.length; i++) {
                        areaSection.append(createAreaLink(response.areas[i]));
                    }
                    var businessSection = $("#businessPanel .datatable tbody");
                    businessSection.html("");
                    businesses = [];
                    google.maps.Map.prototype.clearMarkers();
                    for (var i = 0; i < response.businesses.length; i++) {
                        businessSection.append(createBusinessRow(response.businesses[i]));
                        businesses[businesses.length] = response.businesses[i];
                    }
                    addBusinessesToMap();
                    $.unblockUI();

                },
                dataType: 'json'
            });
        }
        else {
            var area = url.split("/")[2].split(".")[0];
            url = "ajax/business_listbyarea.aspx?area=" + area + "_" + county;
            //history.pushState({}, county, "counties/" + county + "/" + area + ".aspx");

        }

        
        return ($(this).attr("href").split("/").length != 2);
    });





    /* $(".homeLink").click(function () {
    var parent = "Ireland";
    $.ajax({
    url: "ajax/location_list.aspx", cache: false,
    data: { parent: parent },
    success: function (resp) { onListLocationSuccess(resp, parent) },
    error: onSendDeleteEmailException,
    dataType: "json"
    });

    return false;
    });

    addLocationLinkHandler();*/





    /*var over = false;
    $("iframe[ id *= ogle ]").focus(function () {
    if (over) {
    $.ajax({
    type: "post",
    url: "ajax/clientlog_add.aspx",
    data: {
    adUrl: window.location.href,
    screen: screen.width,
    browser: navigator.userAgent
    }
    });
    }
    }).mouseover(function () {
    over = true;
    }).mouseout(function () {
    over = false;
    });*/

});

function createAreaLink(area) {
    var href = "";
    if (area.ParentRef == "Ireland") {
        href = "counties/" + area.Name + ".aspx";
    } else {
        href = "counties/" + area.ParentRef + "/" + area.Name + ".aspx";
    }

    var link = $("<a href='" + href + "'>" + area.Name + "</a>");
    //link.bind("click", function () { alert("click"); });
    return link;
}
var altRowCounter = 0;
function createBusinessRow(business) {
    var href = linkBuilder(business);

    var link = $("<a href='" + href + "'>" + business.Name + "</a>");
    var nameCell = $("<td></td");
    nameCell.append(link);
    var categoryCell = $("<td></td");
    categoryCell.text(business.Category);
    var areaCell = $("<td></td");
    areaCell.text(business.Area.replace("_", ", "));
    var phoneCell = $("<td></td");
    phoneCell.text(business.Phone);

    var row = $("<tr></tr");
    altRowCounter++;
    row.addClass(((altRowCounter % 2) == 1) ? "altrow" : "");
    row.append(nameCell);
    row.append(categoryCell);
    row.append(areaCell);
    row.append(phoneCell);

    return row;
}

function addLocationLinkHandler() {
    $("#locationPanel a").click(function () {
        var county = $.trim($(this).text());
        $.ajax({
            url: "ajax/location_list.aspx", cache: false,
            data: { parent: county },
            success: function (resp) { onListLocationSuccess(resp, county) },
            error: onSendDeleteEmailException,
            dataType: "json"
        });




        return false;
    });
}
function onListLocationSuccess(resp, parent) {
    $("#locationPanel span").html("");
    for (var i = 0; i < resp.length; i++) {
        var root = (parent == "Ireland") ? resp[i] : String.format("{0}/{1}", parent, resp[i]);
        var link = $(String.format("<a href='Counties/{0}.aspx'>{1}</a>", root, resp[i]));
        $("#locationPanel span").append(link);
    }
    if (parent == "Ireland")
        addLocationLinkHandler();
}
function showMenuCategory(obj) {

    if (obj != null)
        $("#categoryPanel").html($("#category_" + obj).html());
    $("#categoryPanel").css("display", "block");
}
function hideMenuCategory(obj) {
    $("#categoryPanel").css("display", "none");
}
function onGetTemplatesResponse(obj) {
    $("#templates").append(obj);
}
function linkBuilder(business) {
    return business.ID + "/" + $.trim(business.Name).replace(/\*/g, " ").replace(/:/g, " ").replace(/ & /g, "-and-").replace(/&/g, "-and-").replace(/\./g, "_").replace("'", "").replace(/\//g, "-").replace(/\?/g, "-").replace(/%/g, "-").replace(/  /g, " ").replace(/ /g, "+") + ".aspx";
}
function linkBuilderArea(area) {
    //return String.Format("<a href='counties/{0}{1}.aspx' title='Businesses in {2}'>{2}</a>", (area.ParentRef != "Ireland") ? area.ParentRef + "/" : "", HttpContext.Current.Server.UrlEncode(area.Name.replace(" & ", "-and-")), HttpContext.Current.Server.HtmlEncode(area.Name));
}
function linkBuilderCounty(county) {
    //return String.Format("<a href='counties/{0}.aspx'>{1}</a>", county.Name);
}
function linkBuilderCategory(category) {
    //return String.Format("<a href='categories/{0}.aspx'>{1}</a>", escape(category.Name.replace(" & ", "-and-").replace("/", "-or-").replace(".", "_")), HttpContext.Current.Server.HtmlEncode(category.Name));
}
var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    latlng = new google.maps.LatLng(latitude, longitude);
    var myOptions = {
        zoom: zoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    if ($("#map_canvas")[0] != null)
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    if (document.getElementById("pano_canvas") != null) {

        var panoramaOptions = {
            position: latlng,
            pov: pov
        };
        panorama = new google.maps.StreetViewPanorama(document.getElementById("pano_canvas"), panoramaOptions);

        map.setStreetView(panorama);


        google.maps.event.addListener(panorama, 'pov_changed', function () {
            setArbInfo();
        });
        google.maps.event.addListener(panorama, 'position_changed', function () {
            setArbInfo();
        });


    }
    addBusinessesToMap();
}
function addBusinessesToMap() {

    var infowindow = new google.maps.InfoWindow({
        content: ""
    });
    var minLat = 90;
    var minLong = 180;
    var maxLat = 0;
    var maxLong = -180;

    var maxBusiness = businesses.length;
    for (var i = 0; i < maxBusiness; i++) {
        if (businesses[i].Position != null) {

            if (businesses[i].Position.Latitude < minLat)
                minLat = businesses[i].Position.Latitude;

            if (businesses[i].Position.Longitude < minLong)
                minLong = businesses[i].Position.Longitude;

            if (businesses[i].Position.Latitude > maxLat)
                maxLat = businesses[i].Position.Latitude;

            if (businesses[i].Position.Longitude > maxLong)
                maxLong = businesses[i].Position.Longitude;

            var thisBusiness = businesses[i];
            (function (thisBusiness) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(thisBusiness.Position.Latitude, thisBusiness.Position.Longitude),
                    map: map,
                    title: thisBusiness.Name
                });
                map.addMarker(marker);
                google.maps.event.addListener(marker, 'click', function () {
                    infowindow.close();
                    infowindow = new google.maps.InfoWindow({
                        content: getBubbleHTML(thisBusiness)
                    });
                    infowindow.open(map, marker);


                });
            })(thisBusiness);

        };
    }
    if ((minLat != 90) && (minLong != 180) && (maxLat != 0) && (maxLong != -180)) {
        minLat = Math.max(minLat, 51.9);
        minLong = Math.max(minLong, -9.5);
        maxLat = Math.min(maxLat, 54.3);
        maxLong = Math.min(maxLong, -6.5);

        if (minLat >= maxLat) {
            minLat = maxLat - .25;
            maxLat = maxLat + .25;
        }
        if (minLong >= maxLong) {
            minLong = maxLong - .05;
            maxLong = maxLong + .05;
        }

        var southWest = new google.maps.LatLng(minLat, minLong);
        var northEast = new google.maps.LatLng(maxLat, maxLong);

        //southWest = new google.maps.LatLng(52.5, -9.5);
        //northEast = new google.maps.LatLng(54.5, -6.5);
        var bounds = new google.maps.LatLngBounds(southWest, northEast);

        map.fitBounds(bounds);
    }

    if (businesses.length == 1) {
        if (businesses[0].Position.Latitude == 0)

            codeAddress(businesses[0]);
    }



}
function test() {
    alert(map.getBounds());
}
function getBubbleHTML(business) {
    var htmlString = '<table>';
    htmlString += '<tr><td>Name:</td><td>' + business.Name + '</td></tr>';
    htmlString += '<tr><td>Category:</td><td>' + business.Category + '</td></tr>';
    htmlString += '<tr><td>Area:</td><td>' + business.Area.replace("_", ",") + '</td></tr>';
    htmlString += '<tr><td>Phone:</td><td>' + business.Phone + '</td></tr>';

    htmlString += '</table>';
    return htmlString;

}
function showManageDialog(businessId) {
    if (isLoggedIn) {
        $("#dialog_manage").html("<table><tr><td colspan='2'>To Manage this listing enter your email and click Manage.</td></tr><tr><td></td><td></td></tr><tr><td>Email:</td><td><input type='text' id='manage_email' /></td></tr></table>");
        $("#dialog_manage").dialog({
            modal: true,
            buttons: {
                'Manage': function () {
                    sendManageEmail($("#manage_email").val(), businessId);
                    $(this).dialog('close');
                },
                Cancel: function () {
                    $(this).dialog('close');
                }
            }
        });


    } else {
        $("#dialog_manage").html("<div>Please create a free account and you can manage this listing.</div>");

        $("#dialog_manage").dialog({
            modal: true,
            buttons: {
                'Signup': function () {
                    window.location = "login.aspx";
                    $(this).dialog('close');
                },
                Cancel: function () {
                    $(this).dialog('close');
                }
            }
        });
    }
}
function sendManageEmail(email, businessId) {

    $.blockUI({ message: '<h1>Please Wait...</h1>', fadeIn: 0 });
    $.ajax({
        url: "ajax/email_delete.aspx", cache: false,
        data: { email: email, businessId: businessId, instruction: 'manage' },
        success: onSendDeleteEmailSuccess,
        error: onSendDeleteEmailException
    });
}
function showDeleteDialog(businessId) {
    $("#dialog_delete").html("<table><tr><td colspan='2'>To Delete this listing enter your email and click Delete.</td></tr><tr><td></td><td></td></tr><tr><td>Email:</td><td><input type='text' id='delete_email' /></td></tr></table>");

    $("#dialog_delete").dialog({
        modal: true,
        buttons: {
            'Delete': function () {
                sendDeleteEmail($("#delete_email").val(), businessId);
                $(this).dialog('close');
            },
            Cancel: function () {
                $(this).dialog('close');
            }
        }
    });
}
function sendDeleteEmail(email, businessId) {

    $.blockUI({ message: '<h1>Please Wait...</h1>', fadeIn: 0 });
    $.ajax({
        url: "ajax/email_delete.aspx", cache: false,
        data: { email: email, businessId: businessId, instruction: 'delete' },
        success: onSendDeleteEmailSuccess,
        error: onSendDeleteEmailException
    });
}
function onSendDeleteEmailSuccess(data) {
    alert("Please click on the link in your email to complete the request.");
    $.unblockUI();
}
function onSendDeleteEmailException(data) {
    alert("Request Failed, Please try again later.");
    $.unblockUI();
}

var countyName = "Dublin";
var i = 0;
var countyArray;

for (i = 1; i < 20; i++) {

    //countyArray[i] = i;


}


var xmlhttpDataRequest;

if (window.ActiveXObject) {
    xmlhttpDataRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
    xmlhttpDataRequest = new XMLHttpRequest();
}


function getData(county) {
    xmlhttpDataRequest.open("GET", "countylist.aspx?county=" + county, false);
    try {
        if (window.ActiveXObject) {
            xmlhttpDataRequest.onreadystatechange = manageResponse;

            xmlhttpDataRequest.send();
        }
        else {
            xmlhttpDataRequest.onreadystatechange = manageResponse;

            if (xmlhttpDataRequest.readyState != 0) { // Must be initialized before we call send. KL
                xmlhttpDataRequest.send(null);
            }
        }
    }
    catch (e) {
        alert("error: " + e);
    }
    end(null)

}


function manageResponse() {
    var responseString;
    switch (xmlhttpDataRequest.readyState) {
        case 2, 3:
            break;
        case 4:
            if (xmlhttpDataRequest.status != 200) return;

            processData(xmlhttpDataRequest.responseText);
            break;
    }
}

function processData(dataString) {
    alert("w");
    document.getElementById("areas").innerHTML = createAreaTable(dataString);

}

function createAreaTable(string) {
    var areaArray = string.split("~");
    var tempTable;
    alert(areaArray.length);
    for (i = 0; i < areaArray.length; i++) {
        alert(areaArray[i]);
        tempTable = tempTable + "<TR><TD>Content" + areaArray[i] + "</TD></TR>";


    }


    alert(tempTable);
    return tempTable;


}

var geocoder;
//var map;

function codeAddress(business) {

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': business.Address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                icon: 'http://www.localbusinesspages.ie/themes/localbusinesspages/images/approx.png'
            });
        } else {
            //alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

