jQuery(function($){
	// Run init functions - code that should be run whenever a new page is loaded into existing DOM
	initFunctions();
    


$('.aap_stats tr:odd').addClass('odd');


	// Make widgets expand and contract
	$('.anyvan-expander').live('click', function(e) {
		var $this = $(this);
		var state;
		$thisParent = $(this).parent();
		$thisParentNext = $thisParent.next(".anyvan-widget-content");
		
		if($thisParent.hasClass(".contracted")){
			$thisParent.removeClass("contracted").addClass("expanded");
			$thisParentNext.show();
			state = 'expanded';
		} else {
			$thisParent.removeClass("expanded").addClass("contracted");
			$thisParentNext.hide();
			state = 'contracted';
		}
		
		var matches = location.pathname.match(/^\/(.+?)(\/|$)/);
		var controller = matches[1];
		if (controller.length === 0) {
			controller = 'home';
		}
		$.post("/ajax-save-page-settings", { page: controller, type: 'widget-state', id: $thisParent.next().attr('id'), state: state });//Will have to check the scope on this change
		return false;
	});
	
	// Make expanding paragraphs
	$('.expander-head').live('click', function() {
		$(this).next().toggle();
		$(this).toggleClass('contracted');
		$(this).toggleClass('expanded');
	});
	
	// Make links with class dialog open in a dialog
	$('.dialog').live('click', function(e){
		var $this = $(this);
		$('#dialog').remove();
		$('body').prepend('<div id="dialog"></div>');
		$('#dialog').dialog({
			closeOnEscape: true,
			draggable: false,
			modal: true,
			resizable: false,
			title: $this.html(),
			height: 600,
			width: 922
		});
		$('#dialog').dialog('open');
		url = $this.attr('href');
		if (url) {
			$.getJSON(url, function (data, loadFlag) {
				if (loadFlag == 'notmodified' || loadFlag == 'success') {
					if (data.redirect !== undefined) {
						window.location = data.redirect;
					}
					$('#dialog').dialog('option', 'title', data.title);
					$('#dialog').html(data.html);
					eval(data.script);
					initFunctions();
				}
			});
		}
		return false;
	});
	
	// Make links with class dialog open in a dialog
	$('#ebayLink').live('click', function(e){
		var $this = $(this);
		$('#dialog').remove();
		$('body').prepend('<div id="dialog" class="ebay"></div>');
		$('#dialog').dialog({
			modal:true,
			resizable: false,
			title: 'eBay Item',
			dialogClass: 'ebayItem',
			height: 210
		});
		$('#dialog').dialog('open');
		url = $this.attr('href');
		if (url) {
			$.getJSON(url, function (data, loadFlag) {
				if (loadFlag == 'notmodified' || loadFlag == 'success') {
					if (data.redirect !== undefined) {
						window.location = data.redirect;
					}
					$('#dialog').dialog('option', 'title', data.title);
					$('#dialog').html(data.html);
					eval(data.script);
					initFunctions();
				}
			});
		}
		return false;
	});
	
	// Bind the summary more/less link
	$('.summary a.summary-more').live('click', function(e) {
		$thisParent = $(this).parent();
		$thisParent.next().attr('style', 'display: inline');
		$thisParent.next().show('fast');
		$thisParent.find('a:last').remove();
		return false;
	});
	$('.summary a.summary-less').live('click', function(e) {
		$thisParent = $(this).parent();
		$thisParent.hide('fast');
		$thisParent.prev().append(' <a href="#" class="summary-more">more</a></span><span>');
		return false;
	});
	
	// Make grids use ajax for all of their links
	$('div.data-grid a:not(.exempt)').live('click', function() {
		var $target = $(this).closest('div.data-grid');
		var type = $target.find('table:first').attr('id');
		var href = $(this).attr('href');
		$target.data('href', href); // Store this for automatic refresh and other uses
		if (href.match(/\?/)) {
			$target.load('/ajax-' + type, href.replace(/^.*?\?/, ''), function() {
				initFunctions();
			});
			return false;
		} else {
			return true;
		}
	});
	
	// Make links with class confirm prompt the user
	$('a.confirm').live('click', function() {
		return confirm('Are you sure?');
	});
	
	// Make help links open in a dialog
	$('.help').live('click', function() {
		$('#dialog-help').remove();
		$('body').prepend('<div id="dialog-help"></div>');
		$('#dialog-help').dialog( { 
			closeOnEscape: true,
			draggable: false,
			modal: true,
			resizable: false,
			title: 'Help',
			height: 185,
			dialogClass: 'helpBox'
		});
		$('#dialog-help').dialog('open');
		//var randomIeFooler = Math.floor(Math.random()*1000000);
		url = $(this).attr('href'); // + '/' + randomIeFooler;
		$.getJSON(url, function (data, loadFlag) {
			if (loadFlag == 'notmodified' || loadFlag == 'success') {
				if (data.redirect !== undefined) {
					window.location = data.redirect;
				}
				$('#dialog-help').html(data.html);
				eval(data.script);
			}
		});
		return false;
	});
	
	// Make report links open in a dialog
		$('.report').live('click', function() {
		$('#dialog-report').remove();
		$('body').prepend('<div id="dialog-report"></div>');
		$('#dialog-report').dialog( { 
			closeOnEscape: true,
			draggable: false,
			modal: true,
			resizable: false,
			title: 'Report',
			height: 185,
			dialogClass: 'reportBox'
		});
		$('#dialog-report').dialog('open');

		url = $(this).attr('href');
		$.getJSON(url, function (data, loadFlag) {
			if (loadFlag == 'notmodified' || loadFlag == 'success') {
				if (data.redirect !== undefined) {
					window.location = data.redirect;
				}
				$('#dialog-report').html(data.html);
				eval(data.script);
			}
		});
		return false;
	});
});

function initFunctions() {
	makeSummaries();
	makeToolTips();
	//Tab functionality in dialog boxes
	tabFunctions();

}

function makeSummaries() {
	$('.summary').each(function() {
		var $this = $(this);
		if (!$this.data('summary_done')) {
			var $thisText = $this.text();
			if ($thisText.length > 200) {
				var summary = $thisText.substr(0, 200);
				var remain = $thisText.substr(201);
				var lastSpaceIndex = summary.lastIndexOf(' ');
				if (lastSpaceIndex > 0) {
					summary = $thisText.substr(0, lastSpaceIndex - 1);
					remain = $thisText.substr(lastSpaceIndex);
				}
				/**
				 * Maybe easier to read, and quicker insertion into the DOM
				 */
				var summaryHTML = '<span>';
				summaryHTML += summary;
				summaryHTML += ' <a href="#" class="summary-more">more</a></span><span>';
				summaryHTML += remain;
				summaryHTML += '<a href="#" class="summary-less">less</a></span>';
				$(this).html(summaryHTML);
				$('span:last', $this).hide();
			}
			$this.data('summary_done', true)
		}
	});
}

function makeToolTips() {
	return true;
}

function frameLoaded(id) {
	if (typeof(frames[id]) == "undefined" || typeof(frames[id].document) == 'undefined') {
		return false;
	}

	if (frames[id].document.childNodes.length > 0 && frames[id].document.childNodes[0].childNodes !== null && frames[id].document.childNodes[0].childNodes.length > 0) {
		if ($('body', frames[id].document).length > 0 && $('body', frames[id].document).html() !== null) {
			return ($('body', frames[id].document).html().length > 0);
		} else {
			return false;
		}
	} else {
		return false;
	}
}

/**
 * Tab Functionality in Dialogs
 */
var tabFunctions = function(){
	//If tabs are in the DOM
	if($("#tabs").length){
		var $tabPanel = $(".tabPanel");
		//Hide all tab panels, not the first
		$tabPanel.not(":first").hide();
		
		$("#tabs a").click(function(e){
			var $this = $(this);
			var selectedTab = $this.attr("class");
			$tabPanel.show().not($("#"+selectedTab)).hide();
			$("#tabs li").removeClass("active");
			$this.parents('li').addClass("active");
			return false;
		});
	}
	
	//Stripe the data grids
	if($(".data-grid").length){
		/*$(".data-grid tr:even").addClass("even");*/
	}
	
	/**
	 * Format the about you dialog page (provider)
	 */
	if($("#about-you").length){
		var nameArray = [
			"trade_assoc_memberships",
			"goods_in_transit_insurance",
			"accepted_payment_methods",
			"default_pickup"];
		$.each(nameArray, function(intIndex, objValue){
			$("label[for="+ objValue +"]").addClass("mainLabelHead");
		});
	}
};

// The following block implements the string.parseJSON method
(function (s) {
 // This prototype has been released into the Public Domain, 2007-03-20
 // Original Authorship: Douglas Crockford
 // Originating Website: http://www.JSON.org
 // Originating URL  : http://www.JSON.org/JSON.js

 // Augment String.prototype. We do this in an immediate anonymous function to
 // avoid defining global variables.

 // m is a table of character substitutions.

 var m = {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '"' : '\\"',
  '\\': '\\\\'
 };

 s.parseJSON = function (filter) {

  // Parsing happens in three stages. In the first stage, we run the text against
  // a regular expression which looks for non-JSON characters. We are especially
  // concerned with '()' and 'new' because they can cause invocation, and '='
  // because it can cause mutation. But just to be safe, we will reject all
  // unexpected characters.

  try {
   if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
    test(this)) {

     // In the second stage we use the eval function to compile the text into a
     // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
     // in JavaScript: it can begin a block or an object literal. We wrap the text
     // in parens to eliminate the ambiguity.

     var j = eval('(' + this + ')');

     // In the optional third stage, we recursively walk the new structure, passing
     // each name/value pair to a filter function for possible transformation.

     if (typeof filter === 'function') {

      function walk(k, v) {
       if (v && typeof v === 'object') {
        for (var i in v) {
         if (v.hasOwnProperty(i)) {
          v[i] = walk(i, v[i]);
         }
        }
       }
       return filter(k, v);
      }

      j = walk('', j);
     }
     return j;
    }
   } catch (e) {

   // Fall through if the regexp test fails.

   }
   throw new SyntaxError("parseJSON");
  };
 }
) (String.prototype);
// End public domain parseJSON block

var map;
var pickupSearch;
var deliverySearch;
function loadGoogleMap(id) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(id));
	}
}

function setMapBounds(topLeftLat, topLeftLng, bottomRightLat, bottomRightLng) {
	var topLeft = new GLatLng(topLeftLat,topLeftLng);
	var bottomRight = new GLatLng(bottomRightLat,bottomRightLng);
	var mapBounds = new GLatLngBounds(topLeft, bottomRight);
	var zoomLevel = Math.min(13,map.getBoundsZoomLevel(mapBounds));
	map.setCenter(mapBounds.getCenter(), zoomLevel);
}
