var gmap;
var gdir;

jQuery.fn.map = function(settings) {
	settings = jQuery.extend({
		name:			null,
		locationsArray:	new Array(),
		zoomControl:	1,
		zoomLevel:		10,
		viewControl:	1,
		linkTitle:      false,
		mapType:        'map',
		hideCopyright:	false,
		latitude:		0,
		longitude:		0
	},settings);

	
	if(!GBrowserIsCompatible()) return false;
	
	var $mapContainer = $(this.get(0));
	var locations = settings.locationsArray; 
	var map = new GMap2($mapContainer[0]);
	
	function _addZoomControl(map) {
		var control = null;
		
		switch(settings.zoomControl) {
			case 1:
				control = new GSmallMapControl();
				break;
			case 2:
				control = new GLargeMapControl();
				break;
			default:
				break;
		}
		if(control == null) return false;
		map.addControl(control);
		return true;
	}
	
	function _addViewControl(map) {
		var control = null;
		
		switch(settings.viewControl) {
			case 1:
				control = new GMapTypeControl();
				break;
			default:
				break;
		}
		if(control == null) return false;
		map.addControl(control);
		return true;
	}
	
	function _findLocations() {
		if(locations.length > 0) return;
		if(settings.latitude != 0 && settings.longitude != 0) {
			locations[0] = {latitude: settings.latitude,
                    longitude: settings.longitude};
		return;
		}
	   var $addresses = $('.location',$mapContainer);
	   
	   $addresses.each(function(i,val) {
	       var $me = $(this);
	       
	       locations[i] = {latitude: $me.attr('latitude'),
	                       longitude: $me.attr('longitude'),
	                       name: $me.attr('name'),
	                       subId: $me.attr('subId')};
	   });
	}
	
	function _addPointToMap(map,data,index) {
			if(data.geocode) {
				var geocoder = new GClientGeocoder();
				geocoder.getLatLng(data.address,function(p) {
					if(!p) {
						//address not found
					} else {
						data.latitude = p.x;
						data.longitude = p.y;
						map.setCenter(p, settings.zoomLevel);
					}
				});
			} else {
				var point = new GLatLng(data.latitude,data.longitude);
			//TODO: ADD hover
			var name = settings.name || jQuery.trim(data.name);
			var marker;
		   if(name) {
			   markerOptions = { title:name };
			  marker = new GMarker(point, markerOptions)
			   GEvent.addListener(marker, "click", function() {
				   if(settings.linkTitle) marker.openInfoWindowHtml('<a href="profile.html?subscription_id='+data.subId+'">'+name+'</a>');
				   else marker.openInfoWindowHtml(name);
		          });

			   map.addOverlay(marker);
		   } else {
			   marker = new GMarker(point);
			   map.addOverlay(marker);
		   }
		   GEvent.addListener(marker,'mouseover',function(){
			   marker.setImage("/images/maps/pins/markeryellow.png");
		   });
		   GEvent.addListener(marker,'mouseout',function(){
			   marker.setImage("/images/maps/pins/markerred.png");
		   });
		}
	}
	
	function _addPointsToMap(map) {
	
	   for(var i=0;i<locations.length;i++) {
            _addPointToMap(map,locations[i],i);
        }
	}
	
	function _map() {
        _findLocations();
        if(locations.length == 0) return;
        if(locations[0] == undefined) return;
        
        var latlngbounds = new GLatLngBounds( );
        for(var i=0;i<locations.length;i++) {
          var data = locations[i];
          var point = new GLatLng(data.latitude,data.longitude);
          latlngbounds.extend(point);
        }
        map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
		//map.setCenter(new GLatLng(locations[0].latitude,locations[0].longitude), settings.zoomLevel);
		
		_addZoomControl(map);
		_addViewControl(map);
        _addPointsToMap(map);
        $mapContainer.attr({map: 'rendered'});
        
        gmap = map;
	}
	
	_map();
};

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            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
        }
        // CAUTION: 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 trackEvent(href,type,id) {
	logClickEvent(href,type,id);
}
function logSearch(href,k,l,s) {
	var d = new Date();
	href = '/searchLog/' + d.getTime();
	if(typeof(clicky)!='undefined') clicky.log(href,'["search","'+k+'","'+l+'",'+s+']','click');
}
function logImpressions(href,search_term,impressionIds) {
	var d = new Date();
	href = '/impressionsLog/' + d.getTime();
	if(typeof(clicky)!='undefined') clicky.log(href, 'impressions ["'+search_term+'"] ' + impressionIds, 'click');
}
function logClickEvent(href,type,id) {
	var d = new Date();
	href = '/' + href + 'Click/' + d.getTime();
	if(typeof(search_term)=='undefined') search_term = '';
	if(typeof(clicky)!='undefined') clicky.log(href,'["'+type+'","'+search_term+'",'+id+']','click');
}

function quickMapSearch(value) {
	if(value) $('#quickMapPhrase').text(value);
	var phrase = $('#quickMapPhrase').text();
	if(phrase == '') phrase = $('#quickMapPhrase').val();
	xmlSearch($('#mapContainer'),phrase,$('#quickMapInput').val());
	return false;
}

function xmlSearch(container,what,where) {
    var count = 0;
    $.ajax({
        type: 'get',
        url: 'searchXml.html',
        dataType: 'xml',
        data: 'keyword='+what+'&where='+where,
        timeout: 15000,
        beforeSend: function() {
            container.empty();
            var div = $(document.createElement('div'));
            var img = $(document.createElement('img'));
            div.addClass('ajaxLoader');
            img.attr({src: 'images/ajax/ajax-loaderLarge.gif'});
            div.append(img);
            container.append(div);
            $('#quickMapSubmit').attr('disabled','disabled');
        },
        error: function(event, request, settings) {
            $('#quickMapSubmit').removeAttr('disabled');
        },
        success: function(data) {
            container.empty();
            $(data).find('listing').each(function(i,val) {
                var ref = $(this);
                var location = ref.find('location');
                count++;
                locations[i] = {latitude: location.attr('latitude'),longitude: location.attr('longitude'),name: ref.attr('name'), subId: ref.attr('subId')};
            });
            if(count > 0) {
                container.map({viewControl: 0,hideCopyright: true,linkTitle: true,locationsArray: locations});
            } else {
                var div = $(document.createElement('div'));
                div.html('No Results Found');
                div.addClass('ajaxLoader');
                container.append(div);
            }
            $('#quickMapSubmit').removeAttr('disabled');
        }
    });
}

function togglePhone(ref) {
	if(!ref) return false;
	ref.parent().toggle();
	return false;
}

/**
 *  Calls save listing controller to add subscription id to saved listing list.
 *
 *  @param subId	subscription id of listing that is being saved
 **/
function saveListing(subId) {
	SavedListingService.addListing(subId, function(data) {
			changeLinkToSaved(subId);
		});
}

function updateSavedListingsOnPage() {
	if(typeof(SavedListingService)=='undefined') return false;
	var saved;
	SavedListingService.getListings(function(data) {
		$(data).each(function(i) {
			changeLinkToSaved(this);
		});
		saved = data;
	});
	$('*[id^=save]').each(function(i) {
		var id = this.id.replace('save','');
		if(!saved) changeLinkToSaveable(id);
		else {
			if(saved.matches(id)) changeLinkToSaved(id);
			else changeLinkToSaveable(id);
		}
	});
}

function changeLinkToSaveable(subId) {
	var element = $('#save'+subId+' b');
	element.replaceWith('<a onclick="logClickEvent($(this).attr(\'href\'),\'save-listing\','+subId+'); saveListing('+subId+'); return false;" rel="nofollow" href="#">Save &amp; Compare</a>');
	
	return true;
}

function changeLinkToSaved(subId) {
	var element = $('#save'+subId+' a');
	element.empty();
	element.replaceWith('<b>Saved</b>');
	
	return true;
}

//HOME MAP SEARCH
var autoSearchIndex = 0;
function loadQuickMapFuncs() {
	$('#quickMapLeft').click(function() {
		var items = $('#mapSearchLinks li');
		var width = 0;
		var maxSize = $('#mapSearchLinks').parent().width();
		var offset = 0;
		var i = autoSearchIndex;
		for(;i<items.size();i++) {
			offset += $(items[i]).width() + 10;
			autoSearchIndex = i;
			if(offset > maxSize) {
				break;
			}
			width+=$(items[i]).width() + 10;
		}
		$('#mapSearchLinks').animate({'left': '-='+width+'px'}, 'slow');
		i = autoSearchIndex;
		offset = 0;
		for(;i<items.size();i++) {
			offset += $(items[i]).width() + 10;
		}
		if(offset < maxSize) $(this).hide();
		$('#quickMapRight').show();
	});
	
	$('#quickMapRight').click(function() {
		var items = $('#mapSearchLinks li');
		var width = 0;
		var maxSize = $('#mapSearchLinks').parent().width();
		var offset = 0;
		var i = autoSearchIndex - 1;
		for(;i>=0;i--) {
			offset += $(items[i]).width() + 10;
			if(offset > maxSize) {
				break;
			}
			autoSearchIndex = i;
			width+=$(items[i]).width() + 10;
		}
		$('#mapSearchLinks').animate({'left': '+='+width+'px'}, 'slow');
		if(autoSearchIndex <= 0) $(this).hide();
		$('#quickMapLeft').show();
	});
}
//END HOME MAP SEARCH

function printDirections() {
	d_addr = $('#dest-addr').val();
	s_addr = $('#from-addr').val();
	w = window.open('/printDirections.html?d_addr='+d_addr+'&s_addr='+s_addr,null,'height=700,width=700,scrollbars=yes,status=no,toolbar=no,menubar=yes,location=no');
	return false;
}

function direc() {
  $('#directions').empty();
  $('#directions-error').empty().hide();
  dP = document.getElementById('directions');
  gdir = new GDirections(gmap, dP);
  GEvent.addListener(gdir, "error", handleGDirectionErrors);
  s_addr = $('#from-addr').val();
  d_addr = $('#dest-addr').val();
  gdir.load('from: '+ s_addr + ' to: ' + d_addr);
  gmap.checkResize();
}

function handleGDirectionErrors() {
	var error_text = '';	

	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		 error_text= 'No corresponding geographic location could be found for one of the specified addresses.';
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		error_txt = 'A geocoding or directions request could not be successfully processed.';
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		error_text = 'Please specify an address.';
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		error_text = 'A directions request could not be successfully parsed.';
	else 
		error_text = 'An unknown error occurred';

	 $('#directions-error').append('<div>' + error_text + '</div.').show(); 
}


function openWidget() {
  window.open("/widgets/grabWidget.html", "_blank", "height=580,width=320,location=0,toolbar=0,status=0,scrollbars=1");
  return false;
 }

var locations = [];
var IMPRESSION_COOKIE = 'ai_imp';

$(document).ready(function() {
	
	$('#searchFormHolder').submit(function() {
		var f = $(this);
		var k = f.find('#keyword_input').val();
		var l = f.find('#location_input').val();
		var s = f.find('#search_radius').val();

		logSearch(f.attr('action'),k,l,s);
	});
	
	if(typeof(pageMode)=='undefined') return;
	
	if(pageMode == 'index') {
		if(typeof(quickMapSearchFlag)=='undefined' || quickMapSearchFlag) quickMapSearch();
		$('#mapSearchLinks a').bind('click',function() {
			$('#mapSearchLinks a').removeClass('active');
			$(this).addClass('active');
			quickMapSearch(jQuery.trim($(this).text()));
			$(this).blur();
			
			return false;
		});
		loadQuickMapFuncs();
	}
	if(pageMode == 'search') {
		var clicky_advanced_disable = 1;
		
		$(".moreDyansLink").click(function() {
		  var dyanId = $(this).attr("dyanId");
		  var md = $('.moreDyans'+dyanId);
		  if($(this).text() == 'More') {
			  $(this).text("Less");
			  md.show();
		  } else {
			  $(this).text('More');
			  md.hide();
		  }
		  $(this).blur();

		  return false;
		});
		updateSavedListingsOnPage();
		$.urlParam = function(name){
			var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
			if( results == null) return "";
			return results[1] || 0;
		}
		var search_terms = $.urlParam('keyword') + "|" + $.urlParam('where') + "|" + $.urlParam('radius');
		if(search_terms != $.cookie(IMPRESSION_COOKIE)) {
			if(impressionIds.length > 2) logImpressions(location.pathname,search_term,impressionIds);
			$.cookie(IMPRESSION_COOKIE,search_terms);
		}
	}
	
	if(pageMode == 'profile') {
		var vc = 1;
		if(typeof(customViewControl)!='undefined') vc = customViewControl;
		var zc = 1;
		if(typeof(customViewControl)!='undefined') zc = customZoomControl;
		$('#mapContainer').map({locationsArray: locations,viewControl: vc,zoomControl: zc});
		
		$('#nextDisplayAd').bind('click',function (e) {
			var imgs = $('#displayAdContainer').find('img');
			var n = 0;
			imgs.each(function(i, val) {
				if($(this).is(':visible')) n = i+1;
				$(this).hide();
			});
			if(n >= imgs.length) n = 0;
			$(imgs[n]).show();
			$('#currentAd').html(n+1);
			return false;
		});
		$('#prevDisplayAd').bind('click',function (e) {
			var imgs = $('#displayAdContainer').find('img');
			var n = 0;
			imgs.each(function(i, val) {
				if($(this).is(':visible')) n = i-1;
				$(this).hide();
			});
			if(n < 0) n = imgs.length - 1;
			$(imgs[n]).show();
			$('#currentAd').html(n+1);
			return false;
		});
		updateSavedListingsOnPage();
	}
	
	if(pageMode == 'directions') {
  		gmap = new GMap2(document.getElementById('map'));
  		gmap.setCenter(new GLatLng(locations[0].latitude,locations[0].longitude), 12);
  		var point = new GLatLng(locations[0].latitude,locations[0].longitude);
  		gmap.addOverlay(new GMarker(point));
  		gmap.setUIToDefault();
	}
});


function logSMSToGetclicky(form, href) {
    var phone = form.areaCode.value+'-'+form.exchange.value+'-'+form.local.value;    
    clicky.log(href, 'SMS to '+phone, 'click');		    
}
function logMobileSearch(k,l) {
	var d = new Date();
	href = '/mobileSearchLog/' + d.getTime();
	if(typeof(clicky)!='undefined') clicky.log(href,'["search","'+k+'","'+l+'"]','click');
}
function logMobileClick(href, type, id) {
	var d = new Date();
	href = '/' + href + ' Click/' + d.getTime();	
	if(typeof(clicky)!='undefined') clicky.log(href,'["'+type+'",'+id+']','click');
}
function logMobileClickToCall(href, type, phone) {
	var d = new Date();
	href = '/' + href + ' Click/' + d.getTime();	
	if(typeof(clicky)!='undefined') clicky.log(href,'["'+type+'","'+phone+'"]','click');
}

var inno = inno || {};
inno.flash = {};
inno.flash.isSupported = function() {
	var b = document.getElementsByTagName("body")[0];
	var o = document.createElement("object");
	o.setAttribute("type", "application/x-shockwave-flash");
	var t = b.appendChild(o);
	if (t) {
		b.removeChild(o);
		t = null;
		return true;
	}
	return false;
}
$(document).ready(function() {
	if (inno.flash.isSupported()) {
	} else {
		$('#flash-upgrade-div').show();
	}
});

function popupCoupon(url) {
	window1=window.open(url,'coupon','toobar=no,resizable=no,directories=no,menubar=no,scrollbar=yes,width=700,height=500,screenX=100,screenY=200,top=50,left=50');
	window1.focus();
	return false;
}
