/*--------------------------------------------------------------------------------
WriteMaps Application Behavior Layer
Author: Scott Jehl
Updated: april 08
--------------------------------------------------------------------------------*/
//writemaps live
var baseURL = '';



//canvas height function
function setCanvas(){
		if($('#viewPort').size()>0) $('#viewPort').height($(window).height() - ($('#viewPort').get(0).scrollTop+ $('#footer').height() +150)); 	
}

//ZOOM SLIDER
function zoomSlider(){	
	$('#area').slider({
		handle: '#knob',
		startValue: 50,
		slide: function(e, ui){
			$('#sitePages').css('font-size', ui.value+50 + '%');
			scrollMap();
		}
	});
}


//Get the width of the sitemap UL and set it as an inline style so the floats don't wrap   --------------------------------------------
function hugSiteMap(){
	if($('#sitemap').size()>0){
		$('#sitemap').width(($('#sitemap li:eq(0)').width()+200)/10+'em');
	}
}

//scroll sitemap to proper position (left for outline, center for map)
function scrollMap(){
	var viewWidth = $('#viewPort').width();
	var formWidth = $('#sitePages').width();
	if(view.getState() == 'map'){
		if(formWidth>viewWidth){
			var pxFromCenter = (viewWidth - (viewWidth * (viewWidth / formWidth))+60)/2;
			$('div#viewPort').scrollLeft(pxFromCenter);
		}
	}
	else {$('div#viewPort').scrollLeft(0);}
	$('div#viewPort').scrollTop(0);
}


// Loop the li's and add first,last--------------------------------------------
function cleanMapStructure(){
	$('ul:empty').parent().find('div.section:eq(0)').removeClass('section').parent().find('ul:empty').remove();
	$('li.page').each(function(){
				//clean up the ID structure
				var thisInt = 1;
				var parentID = 'page';
				var siblingID = '';
				var thisLi = $(this);
				if(thisLi.prev().size()>0){
					siblingID = thisLi.prev().attr('id');
					thisInt = parseInt(siblingID.substring(siblingID.lastIndexOf('_') + 1), 10) + 1;
				}
				thisInt = PadDigits(thisInt, 3);
				
				//if there's an LI parent, grab its id, otherwise use 'page'
				if(thisLi.parents('li.page').size()>0) {parentID = thisLi.parents('li.page').attr('id');}
				thisID = parentID + '_' + thisInt;
				thisLi.attr('id', thisID).find('input:eq(0)').attr('name', thisID);
				thisLi.find('input:eq(1)').attr('name', thisID+'_url');
				thisLi.find('textarea:eq(0)').attr('name', thisID+'_notes');

				//attach first, last, and solo classes
				var thisDiv = thisLi.find('div:eq(0)');
				thisDiv.removeClass('first last solo').parents('ul:eq(0)').removeClass('solo');
				if(thisLi.is(':first-child')){thisDiv.addClass('first');}
				if(thisLi.is(':last-child')){thisDiv.addClass('last');}
				if(thisLi.is(':only-child')){thisDiv.addClass('solo').parents('ul:eq(0)').addClass('solo');}});
}


//validate url
String.prototype.validateUrl = function(url){
	if(this.length>0){
		var j = new RegExp("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
		return j.test(this) ? true : false;
	}
	else {return false;}
}


//PadDigits function: accepts an integer and pads it with a variable number of leading zeroes to meet a total string length
function PadDigits(n, totalDigits) { 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) { 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
}


function assignPageEvents(){
	//SECTION TOGGLES
	$('.toggleSection').livequery("click", function(){  
			if($(this).is('.sectionCol')){
				$(this).parents('li.page:eq(0)').find('ul:eq(0)').css('opacity', 0).show(500, function(){
					$(this).fadeTo(500, 1.0);
				});
				$(this).parents('li.page:eq(0)').find('div.connectContain:eq(0)').addClass('section');
				$(this).removeClass('sectionCol');
				$(this).html('<img src="'+imgs.bullet_toggle_minus+'" />');
				$(this).attr('title', 'Collapse This Section');
			}
			else{
				$(this).parents('li.page:eq(0)').find('ul:eq(0)').fadeTo(100, 0.0001, function(){$(this).hide(800);});
				$(this).parents('li.page:eq(0)').find('div.connectContain:eq(0)').removeClass('section');
				$(this).addClass('sectionCol');
				$(this).html('<img src="'+imgs.bullet_toggle_plus+'" />');
				$(this).attr('title', 'Expand This Section');
			}
			return false;
	});
	//KILL FORM SUBMIT
	$('form#mapForm').submit(function(){//prevent false http form submits
		return false;
	});
	//INPUT FOCUS
	$('#sitePages input.titleText').livequery("focus", function(){		
		$(this).addClass('focus');		
		$(this).next('div.safariWipe').hide();
		if($(this).is('.defaultText')){$(this).val('');}
	});
	//INPUT + TEXTAREA FOCUS
	$('#sitePages input, #sitePages textarea').livequery("focus", function(){
		appHistory.tempState = [$(this).attr('title'), false, mapData(true)];
	});
	//INPUT BLUR
	$('#sitePages input.titleText').livequery("blur", function(){
		$(this).removeClass('focus');
		if($(this).val() == ''){
			$(this).addClass('defaultText');
			$(this).val('New Page');
			$(this).parents('.pageContain:eq(0)').find('.page_meta h4').html('Page Info: New Page');
		}
		else if($(this).is('.defaultText') && $(this).val() != 'New Page'){$(this).removeClass('defaultText');}
		$(this).next('div.safariWipe').show();
	});
	//INPUT KEYUP
	$('#sitePages input.titleText').livequery("keyup", function(){
		var thisAddButton = $(this).parents('li.page:eq(0)').find('a.addPage:eq(0)');
		if($(this).val() == ''){
			$(this).addClass('defaultText');
			thisAddButton.attr('title', 'Add a Page To This Section');
			$(this).parents('.pageContain:eq(0)').find('.page_meta h4').html('Page Info: New Page');
		}
		else{
			$(this).removeClass('defaultText');
			thisAddButton.attr('title', 'Add a Page To The ' + this.value + ' Section');
			$(this).parents('.pageContain:eq(0)').find('.page_meta h4').html('Page Info: ' + this.value);
		}
	});
	//INPUT AND TEXTAREA KEYUP
	$('#sitePages input, #sitePages textarea').livequery("keyup", function(){
		saveStatus.unsave();
		if($(this).is('.pageUrl')){
			var val = $(this).val();
			$(this).siblings('.openUrl').remove();
			if(val.validateUrl()) {
				$(this).after('<a href="javascript://" onclick="window.open(\''+val+'\');" class="openUrl">View</a>');
			}
		}
	});
	//INPUT AND TEXTAREA KEYDOWN
	$('#sitePages input').livequery("keydown", function(event) {		
		evt = event || window.event;
		el = evt.srcElement || evt.target;
		//if enter key is pressed
		if(evt.keyCode == 13){
			$(this).blur();
			return false;
		}
	});

	//INPUT AND TEXTAREA CHANGE
	$('#sitePages input, #sitePages textarea').livequery("change", function(event) {
		appHistory.addToUndo(appHistory.tempState[0], appHistory.tempState[1], appHistory.tempState[2]);
		if($(this).is('.pageUrl')){
			var val = $(this).val();
			$(this).siblings('.openUrl').remove();
			if(val.validateUrl()) {
				$(this).after('<a href="javascript://" onclick="window.open(\''+val+'\');" class="openUrl" title="View URL in New Window">View</a>');
			}
		}
	});




	//ADD PAGE BUTTONS
	$('.addPage').livequery("click", function(){
		appHistory.addToUndo('New Page');
		$(this).parents('li.page:eq(0)').find('ul:eq(0)').show();
		var insertLoc = $(this).parent().attr('id');
		var addType = "user";
		addPage(insertLoc,null,null,null,null,addType);
		return false;
	});
	//DELETE PAGE BUTTONS
	$('.deleteThis').livequery("click", function(){
		appHistory.addToUndo('Delete Page');
		//get the current page
		var thisPageLI = $(this).parents('li.page:eq(0)');
		//get that page's parent
		var pageParentLi = $(this).parents('li.page:eq(1)');
		//if this li has no siblings, kill the section class and remove the empty UL
		if(thisPageLI.siblings().size() < 1){
			pageParentLi.find('div.connectContain:eq(0)').removeClass('section');
			$(this).parents('ul:eq(0)').remove();
		}
		thisPageLI.remove();
		if($('li.page').size()<1) {addPage('sitePages',null,null,null,null, 'user');}
		hugSiteMap();
		cleanMapStructure();
		saveStatus.unsave();
		return false;
	});
	//SAFARI WIPE (adds a bordered div to blot out safari input borders)
	$('div.safariWipe').livequery("click", function(){
			$(this).prev().focus();
			$(this).hide();
	});


$.fn.positionInfo = function(){
			var thisParent = $('#'+$(this).attr('parentID'));
			var parentCenter = thisParent.width() / 2;
			var parentLoc = thisParent.offset();
			$(this).css('top', (parentLoc.top - 120 + $('#viewPort').get(0).scrollTop) / 10 + 'em');
			if(view.state == 'map'){
				$(this).css('left', (parentLoc.left + parentCenter - 140 + $('#viewPort').get(0).scrollLeft) / 10 + 'em');
				
			}
			else{
				$(this).css('left', (parentLoc.left - 50) / 10 + 'em');
			}
			return $(this);
}

//INFO ICON TOGGLES
	$('a.metaToggle').livequery("click", function(){
		var thisPageMeta = $(this).next();
		var parentLiId = $(this).parents('li:eq(0)').attr('id');		
		var thisUrlVal = thisPageMeta.find('input:eq(0)').val();
		var tempPageMeta = thisPageMeta.clone(true).insertAfter('#sitemap').attr('parentID', parentLiId).addClass('tempMeta').positionInfo().fadeIn(400);
		tempPageMeta.find('input:eq(0)').val(thisUrlVal); //safari needed a double check, input val wasn't updating visually
		tempPageMeta.find('a.metaClose:eq(0)').click(function(){
			var tempPageMeta = $(this).parent();
			var tempURL = tempPageMeta.find('input:eq(0)').val();
			var tempNotes = tempPageMeta.find('textarea:eq(0)').val();
			thisPageMeta.find('input.pageUrl').val(tempURL);
			
			thisPageMeta.find('textarea:eq(0)').text(tempNotes);
			//insert click url if valid
			if(tempPageMeta.find('a.openUrl').size()>0) {
				thisPageMeta.find('a.openUrl').remove();
				thisPageMeta.find('input:eq(0)').after('<a href="javascript://" onclick="window.open(\''+tempURL+'\');" class="openUrl" title="View URL in New Window">View</a>');
			}

			if(tempURL != '' && tempURL != 'http://' && tempURL != 'http&#x3A;&#x2F;&#x2F;'){
				thisPageMeta.prev().find('img').attr('src', imgs.information);
			}
			else if( tempNotes != '' && tempNotes != 'No notes as of yet!' && tempNotes != 'No%20notes%20as%20of%20yet!'){
				thisPageMeta.prev().find('img').attr('src', imgs.information);
			}
			else {
				thisPageMeta.prev().find('img').attr('src', imgs.information_off);
			}
			//kill the clone
			tempPageMeta.fadeOut(400, function(){$(this).remove();});
			return false;
		});
		return false;
	});



	/*----------------------------------
	APPLICATION MENU BAR
	----------------------------------*/
	//MENU CLICK
	$('li.appMenu').click(function(){
		if($(this).is('.open')){$(this).removeClass('open');}
		else {
			$(this).addClass('open');
			$(this).siblings('li').removeClass('open');
		}
		return false; 
	});
	//MENU MOUSEOUT
	$('li.appMenu').mouseout(function(){
		var timer = setTimeout(function(){$('li.appMenu').removeClass('open');}, 300);
		$(this).mouseover(function(){clearTimeout(timer);});
	});
	//CLICK AWAY
	$(document).click(function(){$('li.appMenu').removeClass('open');});
	//FILE MENU
	//NEW
	$('#new a').click(function(){
		if(saveStatus.state == 'saved'){
			window.location = baseURL+'/sitemaps/mapBuilder/';
		}
		else{
			modalBox.create('<h2>Unsaved Changes</h2>', '<p>Would you like to save before leaving?</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a><a href="javascript://" id="dontSaveAndNew">Do not Save</a><a href="javascript://" id="saveAndNew">Save</a>');
			//save and proceed
			$('#saveAndNew').click(function(){
				saveMap('new');
				return false;
			});
			//don't save, but proceed
			$('#dontSaveAndNew').click(function(){
				saveStatus.save();
				window.location = baseURL+'/sitemaps/mapBuilder/';
				return false;
			});
		}
		
	return false; 
	});
	//OPEN
	$('#open a').click(function(){
		openMap();
		return false; 
	});
	
	//SAVE
	$('#save a').click(function(){
		saveMap();
		return false; 
	});
		
	//SAVE AS
	$('#saveAs a').click(function(){
		saveMapAs();
		return false; 
	});
	//print button
	$('#print a').click(function(){
		printMode.enable();
		return false; 
	});
	//XML SITEMAP EXPORT
	$('#exportXML a').click(function(){
		var xmlData = xmlMap();
		modalBox.create('<h2>XML Sitemap for SEO</h2>', '<p>Here\'s your Sitemap data in XML format as specified at sitemaps.org, this can be used to help google find the pages on your site more easily. <a href="http://www.sitemaps.org" onclick="window.open(\'http://www.sitemaps.org\'); return false;" title="Open in New Window">More info on XML Sitemaps</a></p> <textarea name="xmlData" id="xmlData">'+xmlData+'</textarea>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');

		return false; 
	});
	//LOCAL BACKUP EXPORT
	$('#exportJSON a').click(function(){
		var jsonData = mapData(true);
		var tempArray = [];
		var interval = 56;
		for(var i =0; i<jsonData.length; i+=interval){
			tempArray.push(jsonData.substring(i, i+interval));
		}
		jsonData = tempArray.join('</span><span class="jsonLine">');

		modalBox.create('<h2>Export Local Backup (JSON)</h2>', '<p>To save a local backup of this sitemap, copy the source code below and save it in a text file.</p> <pre><code><span class="jsonLine">'+jsonData+'</span></code></pre>',  '<a href="javascript://" id="mbCancel" title="Close">Close</a>');

		return false; 
	});
	//LOCAL BACKUP IMPORT
	$('#importJSON a').click(function(){
		modalBox.create('<h2>Import Local Backup (JSON)</h2>', '<p>To restore to a local backup, paste the sitemap source code into the field below. <strong>Reminder:</strong> Only valid WriteMaps JSON schema will be accepted.</p><form action="#"><fieldset><label for="map_source">SiteMap Source: </label><input type="text" id="map_source" name="map_source" /></fieldset></form>', '<a href="javascript://" id="mbCancel">Cancel</a><a href="javascript://" id="mbSave">Import</a>' );
		$('#mbSave').click(function(){
			var jsonData = $('#mbContent form input#map_source').val();
			if(jsonData != ''){
				appHistory.addToUndo('Import Backup');
				jsonData = JSON.parse(jsonData);
				buildMap(jsonData);
			    saveStatus.unsave();
			}
			else {
				$('#mbContent form input#map_source').val('Paste source code here').focus(function(){$(this).val('');});
			}
			return false;
		});
		return false;
	});	
	//SHARING PREFERENCES
	$('#share a').click(function(){
		modalBox.create('<h2>Sharing Preferences</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		if(getMapID()){
			$.ajax({
			   type: "GET",
			   url: baseURL+"/mapfunctions/sharing_preferences?map_id="+getMapID(),
			   success: function(msg){sharingData(msg);}
			 });			 
		}
		else if(getShareID()) {
			$('#mbContent').html('<p>Sharing preferences can not be changed from within a shared sitemap.</p>');
		}
		else{
			$('#mbContent').html('<p>You must save this sitemap before you can share it.</p>');
		}
		return false;
	});
	
	function sharingData(msg){
				msg = $.parseJSON(msg);

		   		if(msg.share_allow == 0){
		   			$('#mbContent').html('<p>This sitemap is not currently being shared.</p>'+
		   			'<p class="choiceExplain">If you would like to share this map, click "<strong>Enable Sharing</strong>" below. To enable sharing with editing abilities, click "<strong>Enable Sharing & Editing</strong>" below.</p> ');
		   			$('#sharingToggle, #sharingToggle_edit').remove();
		   			$('#mbFooter').append('<a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=1&edit_allow=0" id="sharingToggle">Enable Sharing</a><a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=1&edit_allow=1" id="sharingToggle_edit">Enable Sharing & Editing</a>');

		   		}
		   		else if(msg.edit_allow == 0) {
		   			$('#mbContent').html('<p>This sitemap is publicly shared with editing disabled at the following URL:</p>'+
		   			'<p><a href="'+baseURL+'/sitemaps/shareMap/'+msg.share_id+'" onclick="window.open(\''+baseURL+'/sitemaps/shareMap/'+msg.share_id+'\'); return false;" title="Open in New Window">'+msg.share_id+'</a></p>'+
		   			'<p class="choiceExplain">If you would like to disable sharing, click "<strong>Disable Sharing</strong>" below. To enable shared editing of this sitemap, click "<strong>Enable Editing</strong>" below.</p>');
		   			$('#sharingToggle, #sharingToggle_edit').remove();
		   			$('#mbFooter').append('<a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=0&edit_allow=0" id="sharingToggle">Disable sharing</a><a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=1&edit_allow=1" id="sharingToggle_edit">Enable Editing</a>');
		   		}
		   		else {
		   			$('#mbContent').html('<p>This sitemap is publicly shared and editable at the following URL:</p>'+
		   			'<p><a href="'+baseURL+'/sitemaps/shareMap/'+msg.share_id+'" onclick="window.open(\''+baseURL+'/sitemaps/shareMap/'+msg.share_id+'\'); return false;" title="Open in New Window">'+msg.share_id+'</a></p>'+
		   			'<p class="choiceExplain">If you would like to disable sharing, click "<strong>Disable Sharing</strong>" below. To disable shared editing of this sitemap, click "<strong>Disable Editing</strong>" below.</p>');
		   			$('#sharingToggle, #sharingToggle_edit').remove();
		   			$('#mbFooter').append('<a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=0&edit_allow=0" id="sharingToggle">Disable Sharing</a><a href="'+baseURL+'/mapfunctions/sharing_preferences?map_id='+getMapID()+'&share_allow=1&edit_allow=0" id="sharingToggle_edit">Disable Editing</a>');
		   		}

		   		$('#sharingToggle, #sharingToggle_edit').click(function(){
		   			$('#mbContent').html('<p id="loading">Loading...</p>');
		   			$('#sharingToggle').remove();
		   			$.ajax({
					   type: "GET",
					   url: $(this).attr('href'),
					   success: function(msg){sharingData(msg);}
					 });
					 return false;
		   		});
	}
	//EDIT MENU
	//UNDO
	$('#undoLast a').click(function(){
		appHistory.undo();
		return false;
	});
	//REDO
	$('#redoLast a').click(function(){
		appHistory.redo();
		return false;
	});
		
	//close button
	$('#close, #close a').click(function(){
		return true;
	});
	//OVERLAY CLOSE/CANCEL
	$('#mbCancel, #mbClose').livequery("click", function(){
			modalBox.kill();
			return false;
	});
	//HELP
	//WHATS NEW IN WMS
	$('#whatsNew a').click(function(){
		modalBox.create('<h2>What\'s New in WriteMaps</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		$.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/help_whatsNew/",
		   success: function(msg){$('#mbContent').html(msg);}
		 });
		 return false;
	});
	//USING WMS
	$('#usingWriteMaps a').click(function(){
		modalBox.create('<h2>Using WriteMaps</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		$.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/help_usingWriteMaps/",
		   success: function(msg){$('#mbContent').html(msg).pngFix();;}
		 });
		 return false;
	});

	
	/*----------------------------------
	BUTTON BAR
	----------------------------------*/
	//TOGGLE MAP VIEW
	$('#mapView').click(function(){
		view.map();
		return false;
	});	
	//TOGGLE OUTLINE VIEW
	$('#outlineView').click(function(){
		view.outline();
		return false;
	});
	
	//TOGGLE EDIT MODE
	$('#editingMode').click(function(){
		mode.editing();
		return false;
	});	
	//TOGGLE PRESENTATION MODE
	$('#presentationMode').click(function(){
		mode.presentation();
		return false;
	});

}
	

//VIEW STATE TRACKING
var view = {
	state: 'map',
	map: function(){
		$('#viewPort, #viewToggles ul').addClass('map').removeClass('outline');
		$.cookie('view', 'map');
		this.state = 'map';
		hugSiteMap();
		scrollMap();
		if($('div.tempMeta').size()>0){$('div.tempMeta').positionInfo();}},
	outline: function(){
		$('#viewPort, #viewToggles ul').addClass('outline').removeClass('map');
		$.cookie('view', 'outline');
		this.state = 'outline';
		hugSiteMap();
		scrollMap();
		if($('div.tempMeta').size()>0){$('div.tempMeta').positionInfo();}},
	toggle: function(){
		if(this.state == 'map') {this.outline();}
		else {this.map();}},
	loadView: function(){
		//check cookie for map vs outline
		var viewName = $.cookie('view');
		if(viewName){
			if (viewName == 'outline') {view.outline();}
			else {view.map();}}
		else {view.map();}},
	getState: function(){
		return this.state;
	}
};

	
//MODE STATE TRACKING
var mode = {
	state: 'editing',
	editing: function(){
		$('#viewPort, #modeToggles ul').addClass('editing').removeClass('presentation').removeClass('printing');
		$('#viewPort input').focus(function(){this.focus();});
		mode.state = 'editing';
		$.cookie('mode', 'editing');
	},
	presentation: function(){
		$('#viewPort, #modeToggles ul').addClass('presentation').removeClass('editing').removeClass('printing');
		$('#viewPort input').focus(function(){this.blur();});
		mode.state = 'presentation';
		$.cookie('mode', 'presentation');
	},
	loadMode: function(){
		//check cookie for map vs outline
		var modeName = $.cookie('mode');
		if(modeName){
			if (modeName == 'presentation') {mode.presentation();}
			else {mode.editing();}}
		else {mode.editing();}}
};



/* Quick Key Shortcuts
$.hotkeys.add('Ctrl+o', function(){openMap();});
$.hotkeys.add('Ctrl+s', function(){saveMap();});
$.hotkeys.add('Ctrl+Shift+s', function(){saveMapAs();});
$.hotkeys.add('Ctrl+z', function(){appHistory.undo();});
$.hotkeys.add('Ctrl+Shift+z', function(){appHistory.redo();});
$.hotkeys.add('Ctrl+tab', function(){view.toggle();});
*/

	






var printMode = {
	 savedMode: '',
     enable: function(){
     		
        killSorting();
        	
        var screenPrint = $('link[title=screenPrint]').get(0);
	     screenPrint.disabled = true;
	     screenPrint.disabled = false;
	     if($.browser.msie && $.browser.version < 7){$('#sitemap img.pageIcon').attr('src', imgs.page_iePrint);}
         $('#sitemap').draggable({handle: $('#printCrop'), cursor: 'move' });
         $('#viewPort').css('overflow', 'hidden');
     },
     disable: function(){
	     var screenPrint = $('link[title=screenPrint]').get(0);
	     screenPrint.disabled = true;
	     if($.browser.msie && $.browser.version < 7){$('#sitemap img.pageIcon').attr('src', imgs.page);}
        $('#sitemap').draggable('destroy').css({'position': 'relative', 'left': 'auto', 'top': 'auto'});
        $('#viewPort').css('overflow', 'auto');
        hugSiteMap();
        scrollMap();
        	
        setSorting();
	    	
     }
  }  

function whControls(){
	$('#printControls #pageWidth').keyup(function(){
		var w = parseInt($(this).val());
		$('#printCrop').width(w+'in');
	});
	$('#printControls #pageHeight').keyup(function(){
		var h = parseInt($(this).val());
		$('#printCrop').height(h+'in');
	});
	$('#printPrintView').click(function(){
		window.print();
		return false;
	});
	$('#closePrintView').click(function(){
		printMode.disable();
		return false;
	});
}









//ADD PAGE FUNCTION
function addPage(insertLoc, ID, pageName, pageUrl, pageNotes, addType){
	// Setup Parent Node --------------------------------------------
	//assign the insertLoc var to an element with that id
	if(insertLoc) {
		if($('#'+insertLoc).size() <1){//if no parent node
				var tempID = insertLoc.lastIndexOf('_');
				var thisParentID =  insertLoc.substring(0, tempID);
				var addType = "user";
				addPage(thisParentID,null,'Recovered Page',null,null,addType);
				saveStatus.srcStatus = 'unstable';
		}
		insertLoc = $('#'+insertLoc);
	}
	else {insertLoc = $('#page_001');}
	// if the parent is not the fieldset, make parent into a section
	if(insertLoc.is('#sitePages')){}
	else {insertLoc.find('div.connectContain:eq(0)').addClass('section');}
	// Assign Page ID --------------------------------------------
	//assign thisID var either through parent or from passed var
		var thisID = '';
		if(!ID){
			var thisInt = 1;
			var siblingID = '';
			var parentID = '';
			if(insertLoc.find('ul').size() != 0){
				siblingID = insertLoc.find('ul:eq(0) li:last').attr('id');
				thisInt = parseInt(siblingID.substring(siblingID.lastIndexOf('_') + 1), 10) + 1;
			}
			thisInt = PadDigits(thisInt, 3);
			if(insertLoc.attr('id') == 'sitePages'){ parentID = 'page';}
			else {parentID = insertLoc.attr('id');}
			thisID = parentID + '_' + thisInt;
		}
		else{thisID = ID;}
		// Assign Page Name Var --------------------------------------------
		var pageNameINDefault = '';
		var pageClass = 'titleText';
		var addButtonMessage = '';

		if(!pageName || pageName == '' || pageName == null){	
			pageName = pageNameINDefault;
			pageClass = 'titleText defaultText';
			addButtonMessage = 'Add a Page Inside This Section';
			if(addType != 'user') {
				pageName = 'New Page';
			}
		}
		else{addButtonMessage = 'Add a Page To The ' + pageName + ' Section';}
		//if there's no UL parent for the new page, make one
		if(insertLoc.find('ul').size() == 0){
			var ulAttrs = '';
			if($('#sitemap').size() < 1){ ulAttrs = ' id="sitemap" ';}
			insertLoc.append('<ul'+ulAttrs+' class="solo"></ul>');
		}
		else{insertLoc.find('ul:eq(0)').removeClass('solo');}
		//create the New Page Li
		var liID = ' id="'+thisID+'"';

		//status of url/notes:
		var metaStatus = false;
		//url
		var thisURL = 'http://';
		var urlLink = '';
		if(pageUrl && pageUrl != '{page_url}' && pageUrl != thisURL && pageUrl != 'http&#x3A;&#x2F;&#x2F;') {
			thisURL = pageUrl;
			metaStatus = true;
			if(thisURL.validateUrl()) urlLink = '<a href="javascript://" onclick="window.open(\''+thisURL+'\');" class="openUrl" title="View URL in New Window">View</a>';
		}

		//notes
		var thisNotes = 'No notes as of yet!';
		if(pageNotes && pageNotes!= '{page_notes}' && pageNotes != thisNotes && pageNotes != 'No%20notes%20as%20of%20yet!'){ 
			thisNotes = pageNotes;
			metaStatus = true;
		}

		var infoIcon = metaStatus ? imgs.information : imgs.information_off;
		//class
		var liClass = 'class="page"';
		if(insertLoc.find('ul:eq(0)').is('#sitemap')){ liClass = ' class="root page"';}
		var safariWipe = $.browser.safari ? '<div class="safariWipe"></div>' : '';

		

		
			//INSERT EDITABLE PAGE
		insertLoc.find('ul:eq(0)').append('<li'+liID+liClass+'>'+
				'<div class="connectContain">'+
					'<div class="vLine"><div class="line"></div></div>'+
					'<div class="pageContain">'+
						'<img src="'+imgs.page+'" class="pageIcon" title="Drag to sort pages" />'+
						'<a href="javascript://" class="toggleSection" title="Collapse Section"><img src="'+imgs.bullet_toggle_minus+'" /></a>'+
						'<h3><input type="text" name="'+thisID+'" title="Page Title" class="'+pageClass+'" value="'+pageName+'" maxlength="250" />'+safariWipe+'</h3>'+
						'<a href="javascript://" class="deleteThis" title="Delete Page"><img src="'+imgs.cancel+'" /></a>'+
						'<a href="javascript://" class="metaToggle" title="Page Info"><img src="'+infoIcon+'" /></a>'+
						'<div class="page_meta">'+
							'<h4>Page Info: '+pageName+'</h4>'+
							'<label for="'+thisID+'_url">Page URL</label>'+
							'<input type="text" name="'+thisID+'_url" id="'+thisID+'_url" value="'+thisURL+'" class="pageUrl" title="Page URL" maxlength="250" />'+urlLink+
							'<label for="'+thisID+'_notes">Page Notes</label>'+
							'<textarea name="'+thisID+'_notes" id="'+thisID+'_notes" class="pageNotes" title="Page Notes" maxlength="250">'+thisNotes+'</textarea>'+
							'<a href="javascript://" class="metaClose">Done</a>'+
						'</div>'+
					'</div>'+
				'</div>'+
				'<a class="addPage" title="'+addButtonMessage+'"><img src="'+imgs.add+'" /></a>'+
			'</li>');
			
		cleanMapStructure();
		hugSiteMap();
		
		
		if(addType == 'user') {//if user added the page
			saveStatus.unsave(); 
			setSorting();
			insertLoc.find('input.titleText:last').focus();
		}
				
}



//MAP DATA
// Package Map data to JS object (json boolean returns JSON string, otherwise, returns JS object) --------------------------------------------
function mapData(json, noEncode){
	cleanMapStructure();
    var mapData = {};
	mapData.pages = [];
	$('#sitePages li').each(function(i){
		mapData.pages[i] = {};
		mapData.pages[i].id = $(this).attr('id');
		//page name
		if($(this).find('input.titleText:eq(0)').is('.defaultText')){ mapData.pages[i].name = '';}
   	else {
   		if(!noEncode){ mapData.pages[i].name = encodeURIComponent($(this).find('input:eq(0)').val()); }
   		else {mapData.pages[i].name = $(this).find('input:eq(0)').val(); }
   	}
   	//page url
   	if(!noEncode) {mapData.pages[i].url = encodeURIComponent($(this).find('input.pageUrl:eq(0)').val()); }
   	else {mapData.pages[i].url = $(this).find('input.pageUrl:eq(0)').val(); }
   	//page notes
   	if(!noEncode) {mapData.pages[i].notes = encodeURIComponent($(this).find('textarea.pageNotes:eq(0)').val()); }
   	else {mapData.pages[i].notes = $(this).find('textarea.pageNotes:eq(0)').val(); }
	});
	if(json) {mapData = $.toJSON(mapData);}
	return mapData;
}

//CONVERT TO HTML ENTITIES
String.prototype.htmlEntities = function(){
  var chars = ['&',' ','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<','>','¢','£','¤','¥','¦','§','¨','©','ª','«','¬','­','®','¯','°','±','²','³','´','µ','¶','·','¸','¹','º','»','¼','½','¾'];
  var entities = ['amp','agrave','aacute','acirc','atilde','auml','aring','aelig','ccedil','egrave','eacute','ecirc','euml','igrave','iacute','icirc','iuml','eth','ntilde','ograve','oacute','ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc','uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc','Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute','Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde','Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave','Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig','lt','gt','cent','pound','curren','yen','brvbar','sect','uml','copy','ordf','laquo','not','shy','reg','macr','deg','plusmn','sup2','sup3','acute','micro','para','middot','cedil','sup1','ordm','raquo','frac14','frac12','frac34'];
  newString = this;
  for (var i = 0; i < chars.length; i++){
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g');
    newString = newString.replace (myRegExp, '&' + entities[i] + ';');
  }
  return newString;
};

//RETURN XML SITEMAP
function xmlMap(){
	var xmlDocument = '';
	var doctype = '<?xml version="1.0" encoding="UTF-8"?>';
	//doctype = doctype.htmlEntities();
	xmlDocument+=doctype+"\n";

	var urlSet = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
	//urlSet = urlSet.htmlEntities();
	xmlDocument+=urlSet+"\n";
	var urlSetClose = '</urlset>'+"\n";
	//urlSetClose = urlSetClose.htmlEntities();
	var urls = [];
$('#sitePages li').each(function(i){
		var thisUrl = $(this).find('input.pageUrl:eq(0)').val(); 
		var thisPriority = 1.0-($(this).parents('li').size() / $('#sitePages ul').size());
		var thisUrlNode = '<url><loc>'+thisUrl+'</loc><priority>'+thisPriority+'</priority><lastmod>2007-10-05</lastmod><changefreq>hourly</changefreq></url>';
		//thisUrlNode = thisUrlNode.htmlEntities();
		urls.push(thisUrlNode);
	});
	
	xmlDocument+=urls.join('\n')+'\n\n';
	xmlDocument+=urlSetClose;
	return xmlDocument;
}



/* TRIAL FEATURES: This functionality is in bookmarklet stage and is not yet implemented in the application*/
function exportHTML(){
		if(!$.browser.msie){
		var copyMap = $('#sitePages').clone();
		copyMap.find('input.titleText').each(function(){
		var thisTitle = $(this).val();
		var parentLi = $(this).parents('li:eq(0)');
		var pageUrl = parentLi.find('input.pageUrl:eq(0)').val();
		thisTitle = '<a href="'+ pageUrl +'">'+thisTitle+'</a>';
		
		$(this).parents('li:eq(0)').prepend(thisTitle);
		});
		copyMap.find('div, a.addPage, img, h3, h4, label, textarea').remove();
		copyMap.find('ul, li').each(function(){
			var indent = '';
			var depth = $(this).parents('ul, li').each(function(){
				indent = indent + '\t';
			});
			$(this).removeAttr('class').removeAttr('id').removeAttr('style').before("\n"+indent).append("\n"+indent);
		});
		modalBox.create('<h2>Trial Feature: XHTML Sitemap</h2>', '<p>Here\'s your Sitemap data in XHTML format. This can be used to make a clickable site directory on your website. <strong>Note:</strong> Please let us know if you would like this integrated into the application!</p> <textarea name="xmlData" id="xmlData">'+	copyMap.html() +'</textarea>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
	}
	else {
		modalBox.create('<h2>Trial Feature: XHTML Sitemap</h2>', '<p>Sorry, due to technical constraints, this trial feature is not available in Internet Explorer. However, if you are interested in having this feature implemented in WriteMaps, please let us know!</p>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
	}
}


//BUILD MAP FROM JS OBJECT
function buildMap(mapData){
	if(!mapData){ return false;}
	//no pages means new map
	if(mapData.pages.length == 0){
		//cleanup any map that's there
		$('#sitemap').remove();
		addPage('sitePages',null,null,null,null, null);
	}
	else{
		var mapschema = 'valid';
		//check json for valid schema
		
		$(mapData.pages).each(function(){
			if(typeof this.id == "undefined" || typeof this.name == "undefined" || typeof this.url == "undefined" || typeof this.id == "undefined"){
				mapschema = 'invalid';
			}
		});
		
		//schema is good if we got this far		
		//cleanup any map that's there
		if(mapschema == 'valid'){
			$('#sitemap').remove();
			modalBox.kill();
			if($('#initLoader').size()<1){$('#sitePages').after('<p id="initLoader">Loading...</p>');}
			$(mapData.pages).each(function(){
				var thisPageID = this.id;
				var thisPageName = decodeURIComponent(this.name);
				var thisPageUrl = decodeURIComponent(this.url);
				var thisPageNotes = decodeURIComponent(this.notes);
				var tempID = thisPageID.lastIndexOf('_');
				var thisParentID =  thisPageID.substring(0, tempID);
				if(thisParentID == "page") {thisParentID = 'sitePages';}
				setTimeout(function(){addPage(thisParentID, thisPageID, thisPageName, thisPageUrl, thisPageNotes);}, 10);
			});
		}
		else{
				modalBox.create('<h2>Error: Malformed Source Data</h2>', '<p>The sitemap source you have attempted to import has a malformed schema.</p>', '<a href="javascript://" id="mbCancel" title="Close">Close</a>');
		}
	}
	//Done loading, fade the map in and alert the user if there was a recovery
	if (!$.browser.safari && $('#initLoader').size()>0) {$('#sitemap').hide();}
		$('#mapbuilder').css('cursor', 'default');  
		cleanMapStructure();
		$('#initLoader').fadeOut('normal', function(){
			$(this).remove();
			
			if (!$.browser.safari) {$('#sitemap').fadeIn(1500);}
			scrollMap();
			hugSiteMap();
		
		setSorting();			
		if(saveStatus.getSrcStatus() == 'unstable'){
			modalBox.create('<h2>Recovered SiteMap Data</h2>', '<p>Some of your SiteMap source data was damaged and WriteMaps auto-recovered it. Would you like to save your SiteMap?</p>', '<a href="javascript://" id="mbCancel">Do not Save</a><a href="javascript://" id="mbSave">Save</a>');
			$('#mbSave').click(function(){saveMap();});
		}
			
	});
}





	

//PAGE SORTING BEHAVIOR
function setSorting(){
	killSorting();
	$("#sitemap ul:eq(0)").sortable({ 
	    items: "li", 
	    handle: 'img.pageIcon',
	    cursor: 'move',
	    placeholder: 'sortHover',
	    opacity: 0.4,
	    'zIndex': 99999999,
	    start: function(){
	    	appHistory.tempState = ['Page Sorting', false, mapData(true)];
	    },
	    change: function(){saveStatus.unsave();},
	    update: function(){
	    	appHistory.addToUndo(appHistory.tempState[0], appHistory.tempState[1], appHistory.tempState[2]);
	    },
	    stop: function(){setTimeout(function(){cleanMapStructure();}, 200);
	    }
	});
}

function killSorting(){
$("#sitemap  ul:eq(0)").sortable('destroy'); //kill any sort that's already assigned
}

		



//GET MAP ID
function getMapID(){
   return $('#map_id').val(); 
}
//GET SHARED ID
function getShareID(){
   return $('#share_id').val(); 
}

//LOAD A SITEMAP BY EITHER MAP/SHARED ID OR NEW
function loadMap(){
		$('#sitemap').remove();
		if($('#initLoader').size()==0) {$('fieldset').prepend('<p id="initLoader">Loading...</p>');}
		var postParams = {};
	  if(getMapID()) {postParams = { map_id: getMapID()};}
	  else if(getShareID()) {postParams = {share_id: getShareID()};}
	  else {postParams = false;}
	  //Send to loadMap script	  
  	$.getJSON("http://writemaps.com/mapfunctions/loadMap/", postParams, function(json){buildMap(json);});
}


//OVERLAY BEHAVIOR
var modalBox = {
	create: function (header, content, footer){
			$('li.appMenu').removeClass('open');
			$('#overlayScreen').remove();
			$('#mapNames').css('overflow', 'hidden');
			$('body').append('<div id="overlayScreen" style="display: none;"><div id="modalBox"><div id="mbHeader">'+header+'<a href="javascript://" id="mbClose" title="Close">Close</a></div><div id="mbContain"><div id="mbContent">'+content+'</div><div id="mbFooter">'+footer+'</div></div></div></div>');
			$('#overlayScreen').width($('body').width()).height($('body').height());
			$('#overlayScreen').fadeIn(500);
	},
	kill: function(){
			$('#overlayScreen').fadeOut(500, function(){
				$(this).remove();
				$('#mapNames').css('overflow', 'auto');
			});
			
	}
};



//OPEN MAP
function openMap(){
		modalBox.create('<h2>Open a Saved Map</h2>', '<p id="loading">Loading...</p>', '<a href="javascript://" id="mbCancel" title="Cancel">Cancel</a>');
		 $.ajax({
		   type: "GET",
		   url: "http://writemaps.com/mapfunctions/openMenu/",
		   success: function(msg){$('#mbContent').html(msg);}
		 });
}

	
//SAVE MAP
function saveMap(userAction){
	cleanMapStructure();
	var map_id = getMapID();
	var share_id = getShareID();
	if(map_id || share_id){
		modalBox.create('<h2>Save Map</h2>', '<p id="loading">Saving...</p>', '');
		
		$('#sitemap input.defaultText').val('');
		var mapData = {};
		if(map_id) {mapData['map_id'] = map_id;}
		else {mapData['share_id'] = share_id;}
		$('#sitePages li').each(function(i){
			var thisID = $(this).attr('id');
			var thisPageName = $(this).find('input[@type=text]:eq(0)');
			var thisPageUrl = $(this).find('input[@type=text]:eq(1)');
			var thisPageNotes = $(this).find('textarea:eq(0)');

			mapData[thisPageName.attr('name')]= encodeURIComponent(thisPageName.val());
			mapData[thisID+'_url']= encodeURIComponent(thisPageUrl.val());
			mapData[thisID+'_notes']= encodeURIComponent(thisPageNotes.val());
		});

		$('#sitemap input.defaultText').val('New Page');
		
		$.ajax({
			   type: "POST",
			   url: "http://writemaps.com/mapfunctions/saveMap/",
			   data: mapData,
			   success: function(msg){
		   		
		   		if(msg*1 == msg || msg == 'shared save'){
			   		saveStatus.save();
			   		$('#mbContent').html('<p>Save Successful</p>');
				   	if(userAction == 'new') {window.location = baseURL+'/sitemaps/mapBuilder/';}
					    else {modalBox.kill();}
			   		}
			   		else if (msg == 'Error: 401.'){
			   			$('#mbContent').html('<p>Error: Unauthorized attempt to save.</p>');
			   			modalBox.kill();
			   		}
			   }
		 });
	}
	//no current map_id, gotta saveAS	 
	else {saveMapAs(userAction);}
}
	
//SAVE MAP AS
function saveMapAs(userAction){
		modalBox.create('<h2>Save Map As...</h2>', '<form action="#"><fieldset><label for="map_name">New SiteMap Name:</label><input type="text" id="map_name" name="map_name" /></fieldset></form>', '<a href="javascript://" id="mbCancel">Cancel</a><a href="javascript://" id="mbSave">Save</a>' );

		cleanMapStructure();
		$('#mbSave').click(function(){
			$('#mbContent form').trigger("submit");
			return false;
		});
		var postString = '';
		$('#mbContent form').submit(function(){
			$('#mbContent').html('<p>Saving...</p>');
			$('#sitemap input.defaultText').val('');
			var mapData = {};
			mapData['map_name'] = encodeURIComponent($(this).find('input[@type=text]:eq(0)').val());
			$('#sitemap input.defaultText').val('New Page');
			
			if(mapData['map_name'] != ''){
				$('#sitePages li').each(function(i){

					var thisID = $(this).attr('id');
					var thisPageName = $(this).find('input[@type=text]:eq(0)');
					var thisPageUrl = $(this).find('input[@type=text]:eq(1)');
					var thisPageNotes = $(this).find('textarea:eq(0)');
		
					mapData[thisPageName.attr('name')]= encodeURIComponent(thisPageName.val());
					mapData[thisID+'_url']= encodeURIComponent(thisPageUrl.val());
					mapData[thisID+'_notes']= encodeURIComponent(thisPageNotes.val());
				});
			}
			else {
				$(this).find('input[@type=text]:eq(0)').val('Give your sitemap a name!');
				return false;
			}
			
			$.ajax({
			   type: "POST",
			   url: "http://writemaps.com/mapfunctions/saveMap/",
			   data: mapData,
			   success: function(msg){
				   	if(msg*1 == msg){
					   		
				   		saveStatus.save();
					   		
				   		if(userAction == 'new') {window.location = baseURL+'/sitemaps/mapBuilder/';}
				   		else {window.location = baseURL+'/sitemaps/mapBuilder/'+msg;}
				   	}
				   	else {$('#mbContent').html('<p>'+msg+'</p>');}}
			 });
			return false;
		});
}


	
//SAVE STATUS TRACKING
var saveStatus = {
	state: 'saved',
	srcStatus: 'stable',
	save: function(){
		this.state = 'saved';
		this.srcStatus = 'stable';
		window.onbeforeunload = null;
		$('li#save').addClass('disabled');
	},
	unsave: function(){
		this.state = 'unsaved';
		window.onbeforeunload = function(){
			return 'You have unsaved changes in your sitemap. If you would like to save your sitemap, click cancel and save your sitemap before leaving.';
		};
		$('li#save').removeClass('disabled');
	},
	getState: function(){
		return this.state;
	},
	getSrcStatus: function(){
		return this.srcStatus;
	}
};
	


	
//HISTORY TRACKING
var appHistory = {
	undoList: [],
	redoList: [],
	tempState: [], //for saving app state in situations that might need to be tracked depending on a following event
	addToUndo: function(eventName, fromRedo, json){
		if(typeof eventName == 'undefined') { eventName = '';}
		if(typeof json == 'undefined') {json = mapData(true);}
		if(typeof fromRedo == 'undefined'){
			  this.redoList.length = 0;
			  $('#redoLast').addClass('disabled').find('a:eq(0)').html('Redo');
		}
		$('#undoLast').removeClass('disabled').find('a:eq(0)').html('Undo '+eventName);
		this.undoList.push([json,eventName]);
	},
	addToRedo: function(eventName){
		if(typeof eventName == 'undefined') { eventName = '';}
		$('#redoLast').removeClass('disabled').find('a:eq(0)').html('Redo '+eventName);
		this.redoList.push([mapData(true),eventName]);
	},
	undo: function(){
		if(typeof this.undoList[0]!='undefined'){
			this.addToRedo(this.undoList[this.undoList.length-1][1]);
			buildMap(JSON.parse(this.undoList.pop()[0]));
		}
		if(typeof this.undoList[0]=='undefined'){
			$('#undoLast').addClass('disabled').find('a:eq(0)').html('Undo');
			saveStatus.save();
		}
		else {
			$('#undoLast').find('a:eq(0)').html('Undo '+this.undoList[this.undoList.length-1][1]);
		}
		cleanMapStructure();
		setSorting();
	},
	redo: function(){
		if(typeof this.redoList[0]!='undefined'){
			this.addToUndo(this.redoList[this.redoList.length-1][1], true);
			buildMap(JSON.parse(this.redoList.pop()[0]));
		}
		if(typeof this.redoList[0]=='undefined'){$('#redoLast').addClass('disabled').find('a:eq(0)').html('Redo');}
		else {
			$('#redoLast').find('a:eq(0)').html('Redo '+this.redoList[this.redoList.length-1][1]);
		}
		cleanMapStructure();
		setSorting();
	},
	print: function(){
		return this.undoList;
	}
};
	






//IMAGES PRELOADING AND REFERENCING
var imgs = (function(){
	var ext =  ($.browser.msie && $.browser.version < 7) ? 'gif' : 'png'; //extension switch for IE
	var imgsArr = {
		close: '/images/site/close.'+ext,
		modalBoxHeader: '/images/site/bg_modalBox_header.'+ext,
		modalBoxBot: '/images/site/bg_modalBox_bot.'+ext,
		loaderAnim: '/images/site/loaderAnim.gif',
		bullet_toggle_minus: '/images/site/bullet_toggle_minus.'+ext,
		bullet_toggle_plus: '/images/site/bullet_toggle_plus.'+ext,
		page: '/images/site/page.'+ext,
		page_iePrint: '/images/site/page_iePrint.gif',
		cancel: '/images/site/cancel.'+ext,
		information: '/images/site/information.'+ext,
		information_off: '/images/site/information_off.'+ext,
		add: '/images/site/add.'+ext,
		newWin: '/images/site/newWin.gif',
		dropZone: '/images/site/dropZone.gif'
	};
	return imgsArr;
})();

//PRELOAD IMAGES FUNCTION
(function(){
		var loadedImgs = [];
		var i = 0;
		for (property in imgs){
			loadedImgs[i] = new Image();
			loadedImgs[i].src = imgs[property];	
			i++;
		}
})();


	


/*-------------------------------------------------------------------------
DOM READY EVENTS
-------------------------------------------------------------------------*/
$(function(){
		$('#logo').pngFix();
		$('#alertUser').remove();
		view.loadView();
					
		mode.loadMode();
					
		zoomSlider();
		setCanvas();
		assignPageEvents();
		$(window).resize(function () {setCanvas();});
		loadMap();
		whControls();
});









