//OLD CODE - begin

//$(document).ready(function () {
//    $('ul.dropdownlist').each(function () {
//        var $select = $('<select onchange="window.open(this.options[this.selectedIndex].value)"> />');

//        $(this).find('a').each(function () {
//            var $option = $('<option />');            
//            $option.attr('value', $(this).attr('href')).html($(this).html());
//            $select.append($option);
//        });

//        $(this).replaceWith($select);


//        $('.acc_container').hide(); //Hide/close all containers
//        $('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container


//    });

//    $(".toggle_container").hide();

//    $("h2.trigger").click(function () {
//        $(this).toggleClass("active").next().slideToggle("slow");
//    });

//});
//OLD CODE - end
//Function to transform the Condition and Treatment unordered list to dropdown and open the url in the new window.
$(document).ready(function () {
    if ($('ul.dropdownlist') != null) {
        $('ul.dropdownlist').each(function () { //function to transform the unordered list populated from Sitecore to dropdown.
            var $select = $('<select class="selectService" />');
            $select.prepend("<option value='' selected='selected'>Please Select</option>");

            $(this).find('li').each(function () {
                var $option = $('<option />');
                if ($(this).find('a').length) {
                    $(this).find('a').each(function () {
                        $option.attr('value', $(this).attr('href')).html($(this).html());
                    });
                } else {
                    $option.attr('value', $(this).text()).html($(this).html());
                }
                $select.append($option);

            });
            $(this).replaceWith($select);

            $('.acc_container').hide(); //Hide/close all containers
            $('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container
        });


        $(".selectService").change(function () { //open a new window with the selected option from dropdown
            if ($(this).children("option:selected").text() != 'Please Select') {
                window.open(this.options[this.selectedIndex].value);
            }
        });

        $(".toggle_container").hide();

        $("h2.trigger").click(function () {
            $(this).toggleClass("active").next().slideToggle("slow");
        });
    }

});

//* Popup *//
//--indicates the mouse is currently over a div     
var onDiv = false;
//--indicates the mouse is currently over a link     
var onLink = false;
var onHeader = false;
//--indicates that the bubble currently exists     
var bubbleExists = false;     
//--this is the ID of the timeout that will close the window if the user mouseouts the link     
var timeoutID;
var datestr;
var getHeadline;
var getDefaultLink;
function addBubbleMouseovers(divname, mouseoverClass, headline, defaultlink) {    
    //$("." + mouseoverClass).mouseover(function (event) {
//        if (onDiv || onLink) {
//            return false;
//        }
        datestr = mouseoverClass.substring(7);
        getHeadline = headline;
        getDefaultLink = defaultlink;
        onLink = true;
        showBubble(divname);
    //});          
    $("." + mouseoverClass).mouseout(function() {             
        onLink = false;             
        timeoutID = setTimeout(hideBubble, 150);         
        });     
    }      
    function hideBubble() {         
    clearTimeout(timeoutID);
    //--if the mouse isn't on the div then hide the bubble            
    if (bubbleExists && !onDiv && !onHeader) {
        $("#bubbleID").remove();
        bubbleExists = false;
    }
}
function showBubble(divname) {
    //getContent();  
    if (bubbleExists) {
        hideBubble();
    }          
    //var tPosX = event.pageX + 15;
    //var tPosY = event.pageY;
    var monthArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var d_datestr = new Date(datestr.substring(0, 2) + "/" + datestr.substring(2, 4) + "/" + datestr.substring(4, 8));

    var $obj = $('<span id="event_link" />');
    $obj.css("color", "#347235").css("font-weight", "bold");    
    $obj.hover(keepOpen).mouseout(Closeit);
    $obj.text('Events for ' + monthArr[d_datestr.getMonth('MMMM')] + " " + d_datestr.getDate());

    var ulcontent = $('<ul id="popupul" />');     
    var headlineArr = getHeadline.split(';');
    var linkArr = getDefaultLink.split(';');
    headlineArr.each(function (index) {
        var licontent = $('<li />');
        licontent.text(headlineArr[index]).append("<br />" + linkArr[index]);
        ulcontent.prepend(licontent);
    });
    
  //  $('<div ID="bubbleID" style="position: absolute; border: 2px solid #347235; width: 200px; height: auto; background-color: White;left: 50%, top: 50%"></div>').mouseover(keepBubbleOpen).mouseleave(letBubbleClose).appendTo('.tooltip' + datestr).prepend($obj, "<br/>", ulcontent);

    var $popupdiv = $('<div id="bubbleID" />');
    $popupdiv.css("text-align", "center");
    $popupdiv.css("position", "absolute");
    $popupdiv.css("border", "2px solid #347235");
    $popupdiv.css("width", "280px");
    $popupdiv.css("height", "auto");
    $popupdiv.css("background-color", "White");
    
   // alert($tooltip.position().top);
    if (divname == '1') {
        var $tooltip = $('.tooltip' + datestr);
       // alert($tooltip.position().top + ":" + $tooltip.position().top);
        var popupht = $tooltip.position().top + $tooltip.height(); //offset due to positioning of DIVs.        
       // alert(popupht);
        $popupdiv.css("top", popupht);
        $popupdiv.css("left", $tooltip.position().left);
        var $calender1div = $('#calendar1div');
        
        $popupdiv.mouseover(keepBubbleOpen).mouseleave(letBubbleClose).appendTo($calender1div).prepend($obj, ulcontent);
    }
    else if (divname == '2') {
        var $tooltip = $('.tooltip' + datestr);
       // alert($tooltip.position().top);
        var popupht = $tooltip.position().top + $tooltip.height();
       // alert(popupht);
        $popupdiv.css("top", popupht);
        var $calender2div = $('#calendar2div');
        
        $popupdiv.mouseover(keepBubbleOpen).mouseleave(letBubbleClose).appendTo($calender2div).prepend($obj, ulcontent);
    }   
    bubbleExists = true;
}
function keepOpen() {    
    onHeader = true;
}
function Closeit() {
    onHeader = false;
}
function keepBubbleOpen() {
    //alert(onLink);
    onDiv = true;
}
function letBubbleClose() {
    onDiv = false;
    hideBubble();
}
function getContent() {
    var pcontent = $('<p />');
    pcontent.text('test');
    return pcontent;

}
//--TESTING!!!!!     
//$(document).ready(function () {
//    addBubbleMouseovers("tooltip");     
//});








function Show_Popup(date, headline, link) {
    $('td.tooltip').mousemove(function (e) {
        var moveLeft = 20;
        var moveDown = 10;
        // alert(this.title)
        this.t = this.title;
        this.title = "";

        $('#window').show()
          .css('top', e.pageY)
          .css('left', e.pageX)
          .appendTo('body');

        var monthArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var d_date = new Date(date);
        $('#header_content1').text('Events for ' + monthArr[d_date.getMonth('MMMM')] + " " + d_date.getDate()); 

        if (headline != ' ') {
//            var headlineArr = headline.split('<br />');
//            var linkArr = link.split('<br />');
//            var jList = $("#eventList");
            $('.popup_content').text(headline).append(link);
         //   $('.popup_content').text(headlineArr[1] + headlineArr[2]).append(linkArr[1] + linkArr[2]);
//            headlineArr.each(function (index) {                
//                    var pcontent = $('<li />');
//                    pcontent.text(headlineArr[index]).append(linkArr[index]);
//                    pcontent.insertAfter('#header_content');               
//            });

//            $.each(
//                headlineArr,
//                function (intIndex, objValue) {


//                    // Create a new LI HTML element out of the
//                    // current value (in the iteration) and then
//                    // add this value to the list.
//                    jList.append(
//                $("<li>" + objValue + "</li>")
//                )};
         //   $('.popup_content').text(+ "<br />" +  + "<br /><br />" + headlineArr[2] + "<br />" + linkArr[2]);
        }
    });   

    $('td.tooltip').mouseout(function (e) {
        $('#window').fadeOut('slow');

    });
   // $('#popup_content').append("<a )

//    if (link != ' ') {
//        $('#popup_content').text(link);
//        $('#popupATag').attr('href', link);        
//    }
}
function Close_Popup() {   
    $('#window').fadeOut('slow');
}

//* Pagination *//

function Pager(tableName, itemsPerPage) {
    //alert(tableName);
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;

    this.showRecords = function (from, to) {
        var rows = document.getElementById(tableName).rows;
        // i starts from 1 to skip table header row       
        for (var i = 1; i < rows.length; i++) {
            if (i < from || i > to)
                rows[i].style.display = 'none';
//            else if (rows[i].className == "head") {
//                var rowtxt = rows[i].text();
//                rows[0].text().append(rowtxt);
//            }
            else
                rows[i].style.display = '';
        }
    }

    this.showPage = function (pageNumber) {
        if (document.getElementById(tableName) != null) {
            if (!this.inited) {
                alert("not inited");
                return;
            }
        }

        var oldPageAnchor = document.getElementById('pg' + this.currentPage);
        oldPageAnchor.className = 'pg-normal';

        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg' + this.currentPage);
        newPageAnchor.className = 'pg-selected';

        var from = (pageNumber - 1) * itemsPerPage + 1;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }

    this.prev = function () {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    }

    this.next = function () {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }

    this.init = function () {
        if (document.getElementById(tableName) != null) {
            var rows = document.getElementById(tableName).rows;
            var records = (rows.length - 1);
            this.pages = Math.ceil(records / itemsPerPage);
            this.inited = true;
        }
    }

    this.showPageNav = function (pagerName, positionId) {
        if (document.getElementById(tableName) != null) {
            if (!this.inited) {
                alert("not inited");
                return;
            }
        }
        var element = document.getElementById(positionId);

        var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
        for (var page = 1; page <= this.pages; page++)
            pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
        pagerHtml += '<span onclick="' + pagerName + '.next();" class="pg-normal"> Next &#187;</span>';

        element.innerHTML = pagerHtml;
    }
}


//* Google Maps *//

var geocoder;
var map;
var markers = [];

var activeModalShell;
var activeModalOnline;

function closeModal() {
    document.getElementById("modal").className = "modalOff";
}

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        try {
            markers[i].setMap(null);
            markers[i] = null;
        }
        catch (e) { }
    }
    markers.length = 0;
}


function initialize(id) {
	var mapCanvas = document.getElementById("map_canvas");
    if (mapCanvas) {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(33.905886, -84.353932);
        var myOptions = {
            zoom: 7,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(mapCanvas, myOptions);

		if (id != '')
		{
			getLocations(id);
		}
    }
	else
	{
	
	}


}

function initializeSingleLocation(id, sl) {
    var mapCanvas = document.getElementById("map_canvas");
    if (mapCanvas) {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(33.905886, -84.353932);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl: false,
            mapTypeControl: false
        }
        map = new google.maps.Map(mapCanvas, myOptions);
        getLocation(id, sl);
    }


}



function getLocation(id, sl) {

    var bounds = new google.maps.LatLngBounds();
    var lat = 0;
    var divInner = "";
	
	if (sl != '')
	{
		id = id + "=" + sl;
	}
	
    $.ajax({ url: "/locator.asmx/getLocation",
        data: "{'id': '" + id + "'}",
        contentType: "application/json",
        dataType: "json",
        type: "POST",
        success: function (json) {
            var locations = JSON.parse(json.d);

            if (locations.length > 0) {

                for (var x = 0; x < locations.length; x++) {

                    var loc = locations[x];
                    var scid = loc.SCId;

                    divInner += "<p><strong>" + loc.LocationName + "</strong><br />";
                    divInner += loc.Address + "<br />";
                    if (loc.AddressLine2.length > 0) {
                        divInner += loc.AddressLine2 + "<br />";
                    }
                    divInner += loc.City + ", " + loc.State + "  " + loc.Zip + "<br />";


                    divInner += "</p>";
                    divInner += "<p>" + loc.Telephone + "</p>";


                    divInner += "<p><b>How to Find Us</b><br />";
                    var address = loc.Address + "+" + loc.City + "+" + loc.State + "+" + loc.Zip;
                    var url = "http://maps.google.com/maps?f=d&hl=en&q=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;
                    divInner += "<a target=\"_blank\" href=\"" + url + "\">Door to Door Directions</a><br />";

                    url = "http://maps.google.com/maps?f=d&hl=en&saddr=Hartsfield+Jackson+Atlanta+International+Airport&daddr=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;

                    divInner += "<a target=\"_blank\" href=\"" + url + "\">From the Airport</a><br />";

                    url = "http://maps.google.com/maps?f=d&hl=en&q=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;

                    divInner += "<a target=\"_blank\" href=\"" + url + "\">Traffic Report</a>";

                    divInner += "</p></div><p>";


                    var l = new google.maps.LatLng(loc.Latitude, loc.Longitude)
                    var image = loc.ImgIcon;

                    markers[x] = new google.maps.Marker({
                        map: map,
                        position: l,
                        title: loc.LocationName,
                        info_window: loc.SCId
                    });

                    markers.push(markers[x]);
                    map.setCenter(l);

                }

            }
            else {
                divInner = "<p>Your search returned 0 results.</p>";
            }

            document.getElementById("locationResults").innerHTML = divInner;

            if (activeModalShell != undefined) {
                document.getElementById(activeModalShell).className = "modalOff";
            }
			
			//
            //if (elementId != undefined)
			//{
			//	document.getElementById(elementId).className = "modalOn";
			//	activeModalShell = elementId;
			//}
			
			
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error: " + thrownError);
        }

    });

}


$('#mapIt').click(function () {
    var names = [];
    $('#srchPanel input:checked').each(function () {
        names.push(this.name);
    });
    // now names contains all of the names of checked checkboxes 
    // do something with it 
});


function plotLocations(jsonLocations) {

    var locations = JSON.parse(jsonLocations.d);
    var bounds = new google.maps.LatLngBounds();
    
    var divInner = "";

    if (locations.length > 0) {
        divInner = "<p>Your search returned <strong>" + locations.length + "</strong> results.</p>";

        for (var x = 0; x < locations.length; x++) {

            var loc = locations[x];
            var scid = loc.SCId;

            divInner += "<p><strong>" + loc.LocationName + "</strong>";

            divInner += "<span id=\"GoogleMapSearch\"><strong><a href=\"" + loc.PageLink + "\">Visit Location</strong></a>  |   <a href=\"#\" onclick=\"mclick('" + loc.SCId + "','" + loc.PageLink + "');return false;\">View on Map</a></strong><br /></span>";

            divInner += "<br />" + loc.Address;
			
            if (loc.AddressLine2.length > 0) {
                divInner += ", " + loc.AddressLine2;
            }
            divInner += "<br />" + loc.City + ", " + loc.State + "  " + loc.Zip + "<br />";

            divInner += "</p>";

            var l = new google.maps.LatLng(loc.Latitude, loc.Longitude)
            var image = loc.ImgIcon;
			
            markers[x] = new google.maps.Marker({
                map: map,
                position: l,
                icon: image,
                title: loc.LocationName,
                info_window: loc.SCId,
				pageLink: loc.PageLink,
				serviceLine: loc.ServiceLine
            });

            markers.push(markers[x]);

            google.maps.event.addListener(markers[x], 'click',
                        function () { markerClick(this, loc.SCId); });

            bounds.extend(l);

            map.fitBounds(bounds);

        }

    }
    else {
        divInner = "<p>Your search returned 0 results.</p>";
    }
    document.getElementById("locationResults").innerHTML = divInner;
}

function plotDynamicLocations(locs) {
    clearMarkers();
    document.getElementById("locationResults").innerHTML = "";

    document.getElementById
    var R = 6371 * 1.609344;

    getLocations(locs);
}

function getLocations(id) {

    var bounds = new google.maps.LatLngBounds();
    var lat = 0;
	
	$.ajax({ url: "/locator.asmx/getLocations",
        data: "{'id': '" + id + "'}",
        contentType: "application/json",
        dataType: "json",
        type: "POST",
        success: function (json) {
            plotLocations(json);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error: " + thrownError);
        }

    });
}


function mclick(id, pageLink) {
    var infowindow = new google.maps.InfoWindow();
	
	$.ajax({ url: "/locator.asmx/getLocation",
        data: "{'id': '" + id + "'}",
        contentType: "application/json",
        dataType: "json",
        type: "POST",
        success: function (json) {
            var locations = JSON.parse(json.d);
            var divInner = "";

            if (locations.length > 0) {

                for (var x = 0; x < locations.length; x++) {

                    var loc = locations[x];
                    var scid = loc.SCId;

                    divInner += "<p><div id=\"GoogleMapServices\"><table border=\"0\" width=\"95%\"><tr><td width=\"15%\" valign=\"top\">";

                    if (loc.ImgThumb != '') {
                        divInner += "<img src=\" " + loc.ImgThumb + " \" /></td><td valign=\"top\">";
                    }
                    divInner += " <p><strong><a href=\"" + pageLink + "\">" + loc.LocationName + "</strong><br /></a>";

                    divInner += loc.Address;
					
                    if (loc.AddressLine2.length > 0) {
                        divInner += ", " + loc.AddressLine2;
                    }
                    divInner += "<br />" + loc.City + ", " + loc.State + "  " + loc.Zip + "<br />";
                    divInner += loc.County + " County<br/>";
                    divInner += loc.Telephone + "<br/>";
                    divInner += loc.Fax + "<br/>";

                    divInner += "<p><b>How to Find Us</b><br />";
                    var address = loc.Address + "+" + loc.City + "+" + loc.State + "+" + loc.Zip;
                    var url = "http://maps.google.com/maps?f=d&hl=en&q=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;
                    divInner += "<a target=\"_blank\" href=\"" + url + "\">Door to Door Directions</a><br />";

                    url = "http://maps.google.com/maps?f=d&hl=en&saddr=Hartsfield+Jackson+Atlanta+International+Airport&daddr=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;

                    divInner += "<a target=\"_blank\" href=\"" + url + "\">From the Airport</a><br />";

                    url = "http://maps.google.com/maps?f=d&hl=en&q=" + address + "&sll=" + loc.Latitude + "," + loc.Longitude;

                    divInner += "<a target=\"_blank\" href=\"" + url + "\">Traffic Report</a>";

                    divInner += "</p></tr></table></div><p>";

                }

                document.getElementById("tab1_content").innerHTML = divInner;

                if (activeModalShell != undefined) {
                    document.getElementById("modal").className = "modalOff";
                }
				
				var elementId = document.getElementById("modal");
                if (elementId != null && elementId != undefined)
				{
					document.getElementById("modal").className = "modalOn";
				}

            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error: " + thrownError);
        }

    });
}

function markerClick(mark) {
    var id = mark.info_window;
    var page = mark.pageLink;
	if (mark.serviceLine != '')
	{
		
		id = id + "=" + mark.serviceLine;
	}
	
	mclick(id, page);
}


