jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function addMarker(map, latlng, val, title, datalogo, datalocation, path) {
	var infoHTML = '<div><a title="View Profile" href="' + path + '" target="_blank"><img src="' + datalogo + '" width="100" style="float:left"/></a> <a style="padding-left:12px" target="_blank" href="http://maps.google.com/maps?saddr=&amp;daddr=' + latlng[0] + ',' + latlng[1] + '">Get Directions</a><br clear="both"/><b>' + title + '</b><br />' + datalocation.replace(/,,/, ",") + '</div>';
	map.jmap('AddMarker', {
		'pointLatLng': [latlng[0], latlng[1]],
		'pointIsDraggable': true,
		'pointHTML': infoHTML
	},
    function(marker) {
    	$(val).append('<span class="centerOnMap"><a href="javascript:void(null)" title="Center on Map"><img src="/static/images/marker.png" height="16" style="padding-left:10px" /></a></span>');
    	$(val).find('.centerOnMap').click(function() {
    		marker.openInfoWindow(infoHTML);
    		map.jmap('MoveTo', { 'mapCenter': [latlng[0], latlng[1]], 'mapZoom': 4 })
    		if (map.is(":hidden")) {
    			$('#toggleMap').click();
    		}
    	});
    });
}


function showGoogleMap(map){
    
    $('#toggleMap a span').html('Hide');
    $("#toggleMap").unbind("click");
    $.cookie('mapIsOn','1');
    $('#toggleMap').toggle(
        function(){
            $('#toggleMap a span').html('Show');
            $.cookie('mapIsOn','0');
            map.hide();
        },
        function(){
            $('#toggleMap a span').html('Hide');
            $.cookie('mapIsOn','1');
            map.show();
        }
    );
	if ($("table.purchase").length > 0) {
		var moveToCenterLatLng = "";
		window.bounds = new GLatLngBounds();
		map.before('<div id="address"></div>');
		map.css({ height: '290px', width: '100%' });
		map.jmap('init', { 'mapEnableType':true,'mapEnableScrollZoom':true,'mapControl':'default', 'mapType': 'map', 'mapZoom': 1, 'mapShowjMapsIcon': false });
		Mapifies.MapObjects.purchasemap.addControl((new GMapTypeControl()));

		$.each($('table.purchase td[data-location]'), function(j, val) {

			var latlng = "";
			if ($(val).attr('data-latlng') != undefined) {
				latlng = $(val).attr('data-latlng').split(',');
			}
			if (latlng.length > 1) {
				moveToCenterLatLng = latlng;
				window.bounds.extend(new GLatLng(latlng[0], latlng[1]));
				addMarker(map, latlng, val, $(val).attr('title'), $(val).attr('data-logo'), $(val).attr('data-location'), $(val).attr('data-link'))
			} else {
				map.jmap('SearchAddress', {
					'query': $(val).attr('data-location'),
					'returnType': 'getLocations'
				}
                , function(result, options) {
                	var valid = Mapifies.SearchCode(result.Status.code);
                	if (valid.success) {
                		$.each(result.Placemark, function(i, point) {
                			window.bounds.extend(new GLatLng(point.Point.coordinates[1], point.Point.coordinates[0]));
                			moveToCenterLatLng = point.Point.coordinates;
                			//$(val).append('<br />' + point.Point.coordinates[1] + ',' + point.Point.coordinates[0]);
                			addMarker(map, [point.Point.coordinates[1],point.Point.coordinates[0]], val, $(val).attr('title'), $(val).attr('data-logo'), $(val).attr('data-location'), $(val).attr('data-link'))
                		});
                	} else {
                		//$(val).append("<br />Address error.");
                	}
                });
			}

			//if(moveToCenterLatLng.length > 1) map.jmap('MoveTo', { 'mapCenter': [moveToCenterLatLng[1], moveToCenterLatLng[0]], 'mapZoom': 2 })
		});


	}
	var zoomLevel = Mapifies.MapObjects.purchasemap.getBoundsZoomLevel(window.bounds) < 10 ? zoomLevel = Mapifies.MapObjects.purchasemap.getBoundsZoomLevel(window.bounds) : 10;
	if (zoomLevel < 2) zoomLevel = 2;
	Mapifies.MapObjects.purchasemap.setZoom(zoomLevel);
	Mapifies.MapObjects.purchasemap.setCenter(window.bounds.getCenter()); 
}
/*
function hideUnselectedProductColumns(){
    var index = 1;
    $('span input[type=checkbox]').each(function() {
        var index ++;
        if($(this).attr("checked") == "checked"){
            $('table.purchase colgroup col').eq(index).addClass("hide");
        }
    }
}
*/
$(document).ready(function() {
    /*if ($.cookie('listOnlySelectedProducts') == '1'){
        hideUnselectedProductColumns();
    }
    */
	if (GBrowserIsCompatible()) {
		var map = $('#purchasemap');
		if ($("table.purchase").length > 0) {
			map.before('<div id="toggleMap" style="padding-bottom:5px"><a href="javascript:void(null)"><img src="/static/images/map.png" height="24" style="vertical-align:middle;"/></a> <a href="javascript:void(null)"><span>Show</span> Map</a></div>');
			$('#toggleMap').click(function() {
				showGoogleMap(map);
			})
			if ($.cookie('mapIsOn') == '1') showGoogleMap(map);
		}
	}
});
    
    