/**
 * Core Girlports javascript
 * 
 * 
 * @author mitchell amihod
 * 
 * shortcuts are setup OUTSIDE the closure by the tools.js as well
 */

var $EL = 	YAHOO.util.Element;
var $DH = 	Ext.DomHelper;
var $L = 	YAHOO.lang;
var $GP = YAHOO.namespace('GirlPorts');

$GP = function () {
	
	//if(console.formatted !== undefined) { console.formatted = true };
	//Shortcuts - Only accessible within $GP.
	var $D = 	YAHOO.util.Dom;
	var $E = 	YAHOO.util.Event;
	var $L = 	YAHOO.lang;
	
	var flags = { 
				loginAttempts: 0, //Used to track login attempts. After X attempt, show the forgot your password form.
				loggedIn: false,
				appRoot: false,
				slideAdTimeoutId: false, //This holds ID of the timeout to hide the ad. Used to cancel the call if the user manually hies it
				previous_scroll : false,
				data: {}, //Place to put runtime created flags.
				originalInputVals:  {} //Used to store original input field values. 
	};
	
	return {

		dumpFlags: function(flag) {
			console.dir(flags);
		},		

	    /**
	     * Used to get specific flag setting. If flag not provided, returns flag object
	     * @property flag
	     * @type string
	     */
		getFlag: function(flag) {
			
			if(!flag) {
				return flags;
			}
			
			return flags[flag];
			
		},		
		
		 /**
	     * Used to set specific flag setting. 
	     * if object passed in, will replace whichever flags are included
	     * if a string, will set that specific flag
	     * Setter only checks first level. So in the case of flags, there is an originalInputVals property
	     * which can have anything set arbitrarily. 
	     * 
	     * 
	     * @property flag
	     * @type string/object
	     * @type string optional. if flag is a string, just set that value
	     */
		setFlag: function(flag, value) {

			if( !($L.isUndefined(flag)) && ($L.isString(flag) )) {

				//Remove this if to allow arbitrary flag setting. 
				if(!($L.isUndefined(flags[flag]))){
					flags[flag]=value;

					return true;
				} 
				
				return false; 
				
			} else if( !($L.isUndefined(flag)) && ($L.isObject(flag) )) {

				//Is there a better way to do this? Could use merge i suppose, 
				//but then that would add any var, and i want to filter for only preset ones.
				for (setting in flag) {

					if(!($L.isUndefined(this.getFlag(setting))))  {
			 			flags[setting] = flag[setting];
					}
				}
				return true;
			}

			return false;			
		}

	};	//End Closure Wrapper
	
} ();


/* 
 * Error Message Builder.
 * Build div error element
 * 
 * @param {
 * flag: "header message"
 * errors: [error,error...]
 * }
 * @return HTML string
 */
$GP.errorBuilder = function(o) {

	var errorHTML = '<div id="required_alert"><h3><span class="flag">';
	errorHTML += o.flag;
	errorHTML += '</span></h3><ul class="errors">';
	
	//For some weird reason, getting functions attached to the object, like remove. 
	// but length returns proper # of error messages
	var numErrors = o.errors.length;
	for (var i=0; i < numErrors; i++) {
		errorHTML += '<li>'+o.errors[i]+'</li>';
	}
	
	errorHTML += '</ul></div>';
	
	return errorHTML;

};

/*
 * Success Message Builder.
 * 
 * @param {
 * flag: "header message"
 * content: "message body"
 * }
 * @return HTML string
 */
$GP.successBuilder = function(o) {
	//Create the div.
		
	var divhtml = '<div id="success_alert" class="success"><h3>';
	divhtml += o.flag;
	divhtml += '</h3><ul class="success"><li>';
	divhtml += o.content;			
	divhtml += '</li></ul></div>';
	
	return divhtml;

};


/* 
 * Panel Wrapper
 * Creates a panel based on some configs, and returns it
*/
$GP.panel = function (o) {


	//If no parms pass in, make empty object
	var obj = o || {};
	var container = obj.container || document.body;
	var panelId = "panel";
	var ajaxForm = obj.ajaxForm || false;
	var autoclose = obj.autoclose || false;
	var reload = obj.reload || false;
	var redirect = obj.redirect || false;
	var refresh = obj.refresh || false; //If we want to refresh, instead of making a new one.

	var extraObj = {};

	var theFrag = obj.theFrag;
	var configs = 	{ 
					//iframe: true,
					close: false,
					underlay: 'none',
				//	width: '453px',
		  			fixedcenter : true,
		  			visible : false, 
		  			draggable : false,
		  			constraintoviewport : false,
						zIndex:1000,
						//effect: {effect: YAHOO.widget.ContainerEffect.FADE, duration: .3},
						modal: false
		 };
	
	if(obj.refresh == 1) {
		$GP.thePanel.setBody(theFrag);	
									
		return $GP.thePanel;			
	} else {
		
		var thePanel = new YAHOO.widget.Dialog(panelId, 
											configs
											);

		//theDialog.setHeader("Dialogue Header2");
		thePanel.setBody(theFrag);
	
		thePanel.render(container);

		thePanel.showEvent.subscribe(
			function() {
				//To allow person to scroll, and it will follow. 
				//Starting it at fixedcenter is easy way to get it centered
				thePanel.cfg.setProperty('fixedcenter', false);

			}
		);
		

		if(autoclose) {	

			thePanel.showEvent.subscribe(
				function() {
					setTimeout(
						function(){
							thePanel.hide();
						}, 2000
					);
				}
			);
		}
	
		thePanel.hideEvent.subscribe(function () {
		//	var previous_scroll = $GP.getFlag('previous_scroll');
		//	if(previous_scroll != false) {
		//		window.scroll(previous_scroll[0],previous_scroll[1]);				
		//	}
		//	$GP.setFlag('previous_scroll', false );	
		
			//Used mainly for logout page. 
			if(reload !== false) {

				location.reload(true);
			} else if(redirect !== false) {
				location.href = redirect;
			}
			
			
		});
	
		return thePanel;
	}	
};

//Takes in the element trigger, which has info like file name, etc and plays the audio
// @NOTE: Not tested in IE7, since I have no flash on that browser. 
//No reason to think it wont work since it works in Safari (& FF)
$GP.playAudio = function(el) {

	// @TODO: Check if user has flash using JS. If they dont, 
	//just push them to a new page with the mp3
	var filepath = el.href.replace(el.baseURI, '');

	var thisMovie = function (movieName) {
		if (navigator.appName.indexOf ("Microsoft") !=-1) {
			return window[movieName];
		}	
		else {
			return document[movieName];
		}
	};

	var movieName = "player";
	
	// deprecated flash/JS communication
	// thisMovie(movieName).SetVariable("fileName", filepath);
	// thisMovie(movieName).TGotoLabel("_level0","playAudio");
	
	// new flash/JS communication
	thisMovie(movieName).sendAudioToFlash(filepath);
	
};

/*
 * Handles rollovers on images
 * Currently targeted to element having class=rollover
 * original_file.xyz
 * rolloverfile == original_file_o.xyz
 *
 * @TODO: Q: Is it better to just attach a few listeners to the els with 
 * rollover class as oppossed to capturing and analyzing every mouseover?
 *
 */
$GP.rollover = function(e) {

	var el = $E.getTarget(e);
	//For some reason, images inside of buttons arent bubbling up the mouseover/mouseout, 
	//so lets account for it 
	//IMPORTANT - IMG MUST BE FISRT CHILD OF BUTTON!!! No spaces, returns, nuthin!!!!!!
	if(el.tagName.toLowerCase() == 'button') {
		el = $D.getFirstChild(el);	
	}
	
	if( false === $D.hasClass(el, 'rollover') ) { return; }

	var filetype = el.src.substring(el.src.lastIndexOf('.'), el.src.length);

	switch(e.type){
		case 'mouseover':
			el.src = el.src.replace(filetype, '_o'+filetype);
		break;
		case 'mouseout':
			el.src = el.src.replace("_o"+filetype, filetype);
		break;
		default:
			throw('Unexpected e.type in rollover handler');
	}
};

/*
 * To toggle visibility of element
 * Use:
 * <a> Triggers to toggle el have class toggler
 * <a id="foo-bar-target">
 * <el> to toggle will have id of toggler_target
 * This allows for multiple links to trigger same <el> to toggle (ie: in the case of a hide button when content is visible)
 */
$GP.toggler = function (el) {
	
	//Using Visibility to control whether to show or hide.
	var curVisibility = $D.getStyle(el,'visibility'); 

	if( 'visible' == curVisibility ) {
		
		//store the elements current height, to restore once hidden, so its available on the next call.
		var anim = new YAHOO.util.Anim(el, {opacity: {to: 0 }, height: {to:0, unit: '%' } } , .2, YAHOO.util.Easing.easeOut);
		
		//Once the animation is done.
		anim.onComplete.subscribe(
			function () {
				$D.setStyle(el, 'visibility', 'hidden');
				$D.setStyle(el, 'display', 'none');
			}
		);

	} else {
		//Set Opacity to 0, so it doesnt pop in.
		$D.setStyle(el, 'opacity', '0');
		var anim = new YAHOO.util.Anim(el, {opacity: { to: 1 }, height:{ from: 0 , to: 100, unit: '%'} } , .2, YAHOO.util.Easing.easeIn);
	}
	//Set this up first, results in smoother anims, though not on table row efects
	$D.setStyle(el, 'visibility', 'visible');
	
	var displayStyle = (el.tagName.toLowerCase() == 'tr') ? 'table-row' : 'block' ;
	
	//Compensate for IE bug - make it block regardless of if its a tr
	if(YAHOO.env.ua.ie > 0) { displayStyle = 'block';}

	$D.setStyle(el, 'display', displayStyle);
	
	anim.animate();
	
};

/**
//Handles the sliding of the ad div on top of the page.
*/
$GP.slideAdDiv = function(toAnim) {

	//This should match the starting position in the css of the div
	var hiddenPos = -75;
	var attributes = { 
				top: { to: 0 } 
	};

	var upOpacity = 1;
	var downOpacity = 1;

	if(YAHOO.util.Dom.getY(toAnim) >= -1) {
			attributes.top.to = hiddenPos;
			downOpacity = 0;					
	} else {
			upOpacity = 0;
	}
		
	//Set up anims for the Ad copy themselves
		
	var upAdContentAnim = new YAHOO.util.ColorAnim('up_ad_content', {opacity: {to: upOpacity } } , .2);
	upAdContentAnim.onStart.subscribe(function() {
		//We are scrolling up, to show the clickhere to advertise
		if(upOpacity == 1) {
			$D.setStyle('up_ad_content', 'display', 'inline');
		} 	
	}); 

	upAdContentAnim.onComplete.subscribe(function() {
		if(upOpacity == 0) {
			$D.setStyle('up_ad_content', 'display', 'none');	
			downAdContentAnim.animate();
		}
	}); 

	var downAdContentAnim = new YAHOO.util.ColorAnim('down_ad_content', {opacity: {to: downOpacity } } , .2);	
	downAdContentAnim.onStart.subscribe(function() {
		if(downOpacity == 1) {
			$D.setStyle('down_ad_content', 'display', 'inline');
		}
	}); 

	downAdContentAnim.onComplete.subscribe(function() {
		if(downOpacity == 0) {	
			$D.setStyle('down_ad_content', 'display', 'none');
			upAdContentAnim.animate();
			
		}
	}); 

	var anim = new YAHOO.util.Anim(toAnim, attributes, .5, YAHOO.util.Easing.easeOut);
	anim.onStart.subscribe(function() {

		//Show/Hide the diff content.
		if(attributes.top.to == hiddenPos) {
			//We are hiding it, so hide the ad
			downAdContentAnim.animate();
		} else {
			//Show the ad, so begin by hidig the liner.
			upAdContentAnim.animate();
		}
		
	}); 
	
	anim.onComplete.subscribe(function() {
		var iconVal = (downOpacity == 1) ? 'minus' : 'plus';
		$D.get('show_hide_icon').src = '_images/common/top_banner_' + iconVal + '.gif';
		//Swap + for -
	
	});
	anim.animate();
};

/*
*Trigger motion and animation.
*Used by passport for swapping add/remove button
*/
$GP.animate = function(toAnim, motionAttribs, animAttribs) {

	var motion = new YAHOO.util.Motion(toAnim, motionAttribs, .7, YAHOO.util.Easing.easeOutStrong);
	var anim = new YAHOO.util.Anim(toAnim,animAttribs, .9, YAHOO.util.Easing.bounceOut );		

	motion.onStart.subscribe(
		function() {
			anim.animate();
		}
	);

	motion.animate();							
};


/*
* Shows the loading icon
* This is not used in the end. keeping it for now.
*/
$GP.loadingIcon = {
	
	large : function(etype, args, data) {

		$DH.overwrite(data.responseEl, '<div class="center"><img src="_images/common/ajax-circle-loading-petals.gif" /></div>');
		YAHOO.util.Connect.startEvent.unsubscribe($GP.loadingIcon.large);
		
	},
	
	small : function(etype, args, data) {

		$DH.overwrite(data.responseEl, '<img src="_images/common/ajax-small-flower.gif" />');
		YAHOO.util.Connect.startEvent.unsubscribe($GP.loadingIcon.small);
	}
	
};

/*
*Callback for loading a panel.
*/
$GP.loadPanelCallback = {

	success : function(o) {
		if(o.responseText !== undefined){
			YAHOO.log('loadPanelCallback:Response Received');

			var response = $T.JSONParse(o.responseText);

			var responseHTML = response.innerHTML;
			var theBody = $T.create('div', {id: "panelbody"});
			$DH.overwrite(theBody, responseHTML);
			
			var config = {
				"container" : $D.get('container-fullwidth'),
				"theFrag": theBody
			};

			if(response.autoclose !== undefined) {
				config.autoclose = response.autoclose;
			}
			
			if(response.reload !== undefined){
				config.reload = response.reload;
			}

			if(response.redirect !== undefined){
				config.redirect = response.redirect;
			}

			//Refresh a panel already existing
			if(response.refresh !== undefined){
				config.refresh = response.refresh;
			}
			
			//Put the dialog in globally accessible place
			$GP.thePanel = $GP.panel(config);
			
			$GP.thePanel.show();
			
			//Re-Register Form handlers, since we may have loaded in a new one.
			$GP.initSubmitListener();

		}
		
	},
	
	failure : function(o) {
		
	}
};


/*
*Callback for loading a form.
*/
$GP.loadSidebarCallback = {

	success : function(o) {
		if(o.responseText !== undefined){

			var response = $T.JSONParse(o.responseText);

		 	var responseEl = $D.get(response.responseEl);
			var responseHTML = response.innerHTML;

			// @BBUG anim: Breaks buttons in safari. They dont show, and clicking submit
			//		seems to break )submit handler doesnt grab it)
			if(YAHOO.env.ua.webkit > 0){
				$DH.overwrite(responseEl, responseHTML);		
				$GP.initSubmitListener();
			} else {
			
				var anim = new YAHOO.util.ColorAnim(responseEl, {opacity: {to: 0 } } , .2);

				anim.onComplete.subscribe(
					function () {
						$DH.overwrite(responseEl, responseHTML);
						var anim2 = new YAHOO.util.ColorAnim(responseEl, {opacity: {to: 1 } } , .2);

						anim2.onComplete.subscribe( 
							function() {
								//Re-Register Form handlers
								$GP.initSubmitListener();
							}
						);
						anim2.animate();

					}
				);

				anim.animate();				
	
			}
		}	
	},
	
	failure : function(o) {
		
	}
};


/*
*Load Sidebar Forms
*Tailored to the sidebar forms
*@param fName - Name of the form to load
*/
$GP.loadSidebar = function(fName) {
	
	YAHOO.log('loadSidebar:'+fName, 'warn');
	//Setting some vars manually. 
	// @TODO: Rig it up to override if object is passed in instead of string: fName
	
	var fragName = fName+'_form';
	var responseEl = 'passport_wrapper';

	//Setting thisPath because stuff loaded through ajax/action 
	//controller don't have awareness of this->path
	var thisPath = window.location.href;
	
	//if user request login form, reset bad attempts
	if( 'login' == fragName ) {
		$GP.setFlag('loginAttempts',0);
	}

	var extraArgs = "responseEl="+responseEl+"&thisPath="+thisPath;

	YAHOO.util.Connect.resetFormState();
//	YAHOO.util.Connect.startEvent.subscribe($GP.loadingIcon.large, {'responseEl': responseEl });
	var request = YAHOO.util.Connect.asyncRequest('POST', 'action/loadSidebarForm/'+fragName, $GP.loadSidebarCallback, extraArgs);
	

};

/*
*Load frags of html for shoving into panels
*@param fName - Name of the form to load
*@param o - extraargs / config options
*/
$GP.loadPanel = function(fName, o) {
	YAHOO.log('loadPanel:'+fName, 'warn');
	
	//Setting some vars manually. 
	// @TODO: Rig it up to override if object is passed in instead of string: fName
	
	var fragName = fName;
	var obj = o || {};
	
	//var responseEl = 'passport_wrapper';
	
	//Setting thisPath because stuff loaded through ajax/action 
	//controller don't have awareness of this->path
	var thisPath = window.location.href;
	var extraArgs = "thisPath="+thisPath;
	
	//if user request login form, reset bad attempts
	if( 'login' == fragName ) {
		$GP.setFlag('loginAttempts',0);
	}
	
	if(obj.confirm_delete !== undefined) {
		extraArgs += '&'+obj.confirm_delete;
	} 

	if(obj.confirm_dest_1 !== undefined) {
		extraArgs += '&'+obj.confirm_dest_1;
	} 

	if(obj.confirm_dest_2 !== undefined) {
		extraArgs += '&'+obj.confirm_dest_2+'&refresh=1';
	} 

	if(obj.destinationId !== undefined){
		extraArgs += '&destination_id='+obj.destinationId;
	}

	if(obj.autoclose !== undefined){
		extraArgs += '&autoclose='+obj.autoclose;
	}

	if(obj.reload !== undefined){
		extraArgs += '&reload=1';
	}
	
	if(obj.redirect !== undefined){
		extraArgs += '&redirect='+obj.redirect;
	}
	

	YAHOO.log("exta args - load panel: "+extraArgs);
	YAHOO.util.Connect.resetFormState();
	var request = YAHOO.util.Connect.asyncRequest('POST', 'action/loadPanelFrag/'+fragName, $GP.loadPanelCallback, extraArgs);

};

$GP.delDestCallback = {
	success: function(o) {
		YAHOO.log('delDestSuccess');
		if(o.responseText !== undefined){

			YAHOO.log('reload');	
			location.reload(true);
		}
	
	},
  	
	failure: function(o) {
		
	}
};


/*
*Callback for  Delete From Passport when user logged in, on mypassport page
*/
$GP.confirmDeleteCallback = {

	success : function(o) {

		if(o.responseText !== undefined){
			var response = $T.JSONParse(o.responseText);
			
			$DH.overwrite($D.get('mypasscon'), response.innerHTML);
			
			$GP.thePanel.hideEvent.subscribe(
				function() {
						
					var listingId = response.params.data['listing_id'];
					var markerId = response.params.data['marker_id'];
					//replace the old with new button

					//Animation setup
					var toAnim = $D.get('listing-'+listingId);

					var rpoint = $D.getXY(toAnim);
					var xy_anim = [rpoint[0], rpoint[1]+150];	
					var points = { to: xy_anim};		
					var motionAttribs = { points:  points };
					var animAttribs = {opacity: { to: 0 } };

					var motion = new YAHOO.util.Motion(toAnim, motionAttribs, 1.0, YAHOO.util.Easing.easeOutStrong);
					var anim = new YAHOO.util.Anim(toAnim,animAttribs, 1.3, YAHOO.util.Easing.bounceOut );		

					motion.onStart.subscribe(
						function() {
							anim.animate();
						}
					);

					anim.onComplete.subscribe(
						function() {

							toAnim.parentNode.removeChild(toAnim);
							//ok, this is whats causing it to fail, albeit silently - suppossed to be returning -1 for markers that dont exist
							if(parseInt(markerId,10) >= 0) {
								$GMmap.removeMarker(markerId);
							}
							
							//check if swapMap is set, if so, swap out for image. 
							if(response.swapMap) {
								$DH.overwrite($D.get('map'), response.swapMap);
							}
							//force a reload of the page if there's no more listings in this city, and the passport isnt empty.

							var listingCon = $D.get('listingsPassportCon');
							//This handles reloading the page when there are no more listing on this page!
						
							if(listingCon.getElementsByTagName('div').length == 0) {
						
									location.reload(true);
							}
							
						}
					);

					motion.animate();

				}
			);

			$GP.thePanel.hide();
		}	
	},
	
	failure : function(o) {
		
	}
};

/*
*Callback for Add and Delete From Passport when user logged in, on desitnation page
*Code from prototype. Works, but could use refactoring
*/
$GP.PassportCallback = {

	success : function(o) {
		if(o.responseText !== undefined){
			YAHOO.log('PassportCallback:Response Received', 'warn');

			var response = $T.JSONParse(o.responseText);

			switch(true) {

				case(response.error !== undefined) : //do we have errors?

				break;

				case(response.success !== undefined) :
				
					//If there's a sidebar passport, update it
					if($D.get('mypassportview') ) {
						var thePassport = $T.create('div', {id: "mypassportview"});
						var thePassportHTML = '<div id="mypassportview">'+response.innerHTML+'</div>';
						//thePassport.innerHTML = response.innerHTML;
						$DH.overwrite($D.get('mypassportview'), thePassportHTML);
					}
				
					// @todo: extract
					//if we're not on #mypassport page, whose body has an id of mypassport
					if('mypassport' != document.body.id) {

						var swapOld = response.params['swapOld'];
						var swapNew = response.params['swapNew'];

						var listingId = response.params.data['listing_id'];
						//replace the old with new button
						var oldForm = $D.get(swapOld+'_form-' + listingId);
						var oldButton = $D.get('but-'+swapOld + '-' + listingId );
						var oldButtonImage = oldButton.firstChild;
						
						//Safari compensation
						oldForm.safari_comp.value = swapNew;
						
						//Old form out, new vals in
						oldForm.id = swapNew+'_form-' + listingId;
						oldButton.id = 'but-' + swapNew + '-' + listingId ;
						oldButton.name = 'do['+ swapNew +']';
						
						$DH.overwrite(oldButton,'<img alt="'+swapNew+'" src="_images/en/common/'+swapNew+'.gif" />');
						
					}
				break;
				default:
					throw "Unexpected response";
			}

		}	
	},
	
	failure : function(o) {
		
	}
};

/*
*Callback for form submissions.
*/
$GP.submitHandlerCallback = {

	success : function(o) {
		if(o.responseText !== undefined){

			var response = $T.JSONParse(o.responseText);

			switch(true) {

				case(response.error !== undefined) : //do we have errors?

					var responseEl = $D.get(response.params.responseEl);
					var errorHTML = $GP.errorBuilder({
						'flag' : response.error,
						'errors' : response.errors	
					});

					$DH.overwrite(responseEl, errorHTML);

					//Need to compensate for response el being hidden previously,because for some reason xxx
					//so maybe they will want to comment 2x in a row on the same item???
					if($D.getStyle(responseEl, 'visibility') == 'hidden') {
						$D.setStyle(responseEl, 'visibility', 'visible');
						$D.setStyle(responseEl, 'opacity', '1');
						$D.setStyle(responseEl, 'display', 'block');							
					}

					// @TODO add back in display of forgot form when user tries to login wrong more then 3 times.
				break;

				case(response.success !== undefined) :
					//Success case, so find out what action to do
					//Not using eval due to earlier problem, but it still may be a long term option.
					//Possible Actions:
					//redirect - load a new page
					//swap - look for response.params.swapEl to replace entirely with new content

					var responseEl;

					if (response.form_reset!== undefined) {
					
						$GP.formReset(o.argument.form);
												
					}

 					if (response.flag!== undefined) {

						//No swapEl? Then use the response el.						
						//Sometimes, we will want diff
						//  container for success over error, so used swapEl as parm for that in form

//issue is WE NEED TO HIDE reponspeEL, + toggler el, ie: hide thanks message, then trigger form hider.
						responseElId = response.params.swapEl || response.params.responseEl;

						responseEl =  $D.get(responseElId);

						var divhtml = $GP.successBuilder({ 'flag': response.flag, 'content' : response.content});

						$DH.overwrite(responseEl, divhtml);
						
						//Need to compensate for response el being hidden previously,because for some reason xxx
						//so maybe they will want to comment 2x in a row on the same item???
					
						if($D.getStyle(responseEl, 'visibility') == 'hidden') {
							$D.setStyle(responseEl, 'visibility', 'visible');
							$D.setStyle(responseEl, 'opacity', '1');
							$D.setStyle(responseEl, 'display', 'block');							
						}
						
						//if there IS a swap el, then we know response el is most likely the error message, so lets empty that out.
						if(response.params.swapEl){
							oldError = $D.get(response.params.responseEl);
							if(oldError) {
								oldError.innerHTML = '';
							}

						}
					}

					//Tells us to hide the message after X seconds
					if(response.hide !== undefined) {
						var ticks = response.hide*1000;

						//There can be certain parms passed back. So, in the case of comments thereis the response el to hide
						//but on top of that, we want to toggle the comment form visi too, so thereis a params.toggleEl as well.
						//For toggler/ie7 - doesnt inherit visibility properly (doesnt give computed one)
						//so setting it explicitly.
						$D.setStyle(responseEl, 'visibility', 'visible');						
						setTimeout(function(){$GP.toggler(responseEl);}, ticks);
						
						if(response.params.toggleEl) {
								setTimeout(function(){$GP.toggler($D.get(response.params.toggleEl));}, ticks);
						}
						
					}

					if(response.panel !== undefined) {
						var extraargs = {};
						if(response.autoclose !== undefined){
							extraargs  = {'autoclose': response.autoclose};
						}
						
						if(response.reload !== undefined){
							extraargs.reload = 1;
						}

						if(response.redirect !== undefined){
							extraargs.redirect = response.redirect;
						}

						$GP.loadPanel(response.panel, extraargs);
						
					} else if (response.redirect !== undefined) {
						//Redirect to on_success
						// @BBUG
						//When feeding a relative url, ie seems to double append it
						//eg: login on http://www.girlports.com/lesbiantravel/destinations/amsterdam
						//the redirect leads page to try to load:
						//http://www.girlports.com/lesbiantravel/destinations/destinations/amsterdam
						var newlocation = response.params.on_success || location.href+"?no_success_url";						
						if(YAHOO.env.ua.ie > 0 ) {
							//NOTE: GpAppRoot is set in the _layouts/main.php - for timing reasons, its just a global
							newlocation = GpAppRoot + newlocation;
						}
						location.href= newlocation;
					}

					if(response.reload !== undefined){
						//While this SHOULD work, it seems like it was causing hangs in certain cases, so went with more direct
						// location.href = location.href which seems to work
						 location.reload(true);
					}


					//Tells us to close the panel after X seconds
					if(response.closepanel !== undefined) {
						var ticks = response.closepanel*1000;
						setTimeout(function(){$GP.thePanel.hide();}, ticks);
					}
		
					if(response.newwindow !== undefined) {
						//open new window on_success
						// @BBUG
						//When feeding a relative url, ie seems to double append it
						//eg: login on http://www.girlports.com/lesbiantravel/destinations/amsterdam
						//the redirect leads page to try to load:
						//http://www.girlports.com/lesbiantravel/destinations/destinations/amsterdam
						var newlocation = response.params.on_success || location.href+"?no_success_url";
						if(YAHOO.env.ua.ie > 0 ) {
							//NOTE: GpAppRoot is set in the _layouts/main.php - for timing reasons, its just a global
							newlocation = GpAppRoot + newlocation;
						}

						window.open(newlocation, '_blank');
					}

					
				break;
				default:
					throw "Unexpected response";
			}

		}	
	},
	
	failure : function(o) {
		
	}
};


/*
* Handlers come at the end, so they can access all of $GP
* IE7/Safari/FF: clickHandler captures the event submit event as a click first. 
* If stopEvent is set, the submit event never fires
* In theory, the click handler only has to manage links. anything else, it can ignore and let through
*
*/
$GP.clickHandler = function(e) {
	//$E.stopEvent(e);

	var passThru = true; //default: should be true to allow links to go through when necessary
	var elTarget = $E.getTarget(e);

	//Sometimes, we will use something other than text in a link
	//example:
	//Often, to make faux-buttons, we will use an <a><span class="button">Foo</span></a>
	//Or, safarifor instance, will say target was image, while everyone else says anchor.
	//So, let's look for an ancestor of span to get real target
	
	//Ok: Some weirdness with buttons and a 1 pixel pad/border that can't be got rid of,
	// so we have to change all the close buttons to actually use button tag
	//so we compensate for that here.

//Safari records the click as an IMG, instead of the button, so lets compensate for that

	if((YAHOO.env.ua.webkit > 0) && ('img' == elTarget.tagName.toLowerCase()) ) {
		var tempTarget = $D.getAncestorByTagName(elTarget, 'button');
		if(!YAHOO.lang.isNull(tempTarget)) {
			elTarget = tempTarget;
		}		
	}

	if( 'a' != elTarget.tagName.toLowerCase() && !('button' == elTarget.tagName.toLowerCase() && $D.hasClass(elTarget, 'fauxlink')) ) {
		var tempTarget = $D.getAncestorByTagName(elTarget, 'a');
		if(YAHOO.lang.isNull(tempTarget)) {
			return;			
		} else {
			elTarget = tempTarget;
		}

	}
	
	//EXTERNAL/INTERNAL Link Targets
	//This marks a link as open target='_blank' if external
	//The check for A is currently redundant, if we are returning anything !=a
	if( 'a' == elTarget.tagName.toLowerCase() ) {

		var href = window.location.hostname;
	    // make the regex
	    var re = new RegExp('\\b' + href + '\\b', "i");

		//Check if its an external link
        if (elTarget.href.search(re) == -1) {
			passThru = true;
            elTarget.target = "_blank";
        }

	}
	
	//ID of links that do something should be in format of:
	//uid-action-target-extra-args
	var command = elTarget.id.split('-')[1];
	var target = elTarget.id.split('-')[2];

	//Command Routing. Doing this long hand, since certain tricks
	//(using eval to route) werent working cross browser

	switch(true) {

		case($D.hasClass(elTarget, 'toggler')):
			$GP.toggler($D.get("toggler_"+target));
			passThru = false;
		break;

		//Specific to the forms in the sidebar - login, forgot, register
		//Load the specific form, and replace 
		case(command == 'load'):

			$GP.loadSidebar(target);

		//people can come from the do you want to create-passport dialog, so close that if its showing.

      if($GP.thePanel && $GP.thePanel.cfg.getProperty('visible')) {
        $GP.thePanel.hide();
        YAHOO.util.Event.onAvailable('register_head', function() {
          var flashEl = $D.get('register_head');
          //needs padding, so apply the class
          YAHOO.util.Dom.addClass(flashEl, 'pad5');
          $GP.flash($D.get('register_head'));
          self.location.hash = '#regform';
        });
      }

			passThru = false;
		break;

		case(command == 'panel'):

			var extraArgs = {};
			
			if(target == 'confirm_delete') {	
				var markerId = elTarget.id.split('-')[4] || '-1';
				extraArgs.confirm_delete = "marker_id="+markerId+"&listing_id="+elTarget.id.split('-')[3];
				
			} else if (target == 'confirm_dest_delete_1') {	
				extraArgs.confirm_dest_1  = "destination_id="+elTarget.id.split('-')[3];
			} else if (target == 'confirm_dest_delete_2') {	
				extraArgs.confirm_dest_2  = "destination_id="+elTarget.id.split('-')[3];	
			} else if((target == 'sendemail') || (target == 'printform')) {
				extraArgs.destinationId = elTarget.id.split('-')[3];
			}
			
			if (target == 'dest_delete'){
				
				if( 'span' == elTarget.tagName.toLowerCase()) {
					elTarget = elTarget.parentNode; //get the A which has the href we need
				}
				YAHOO.util.Connect.resetFormState();
				var request = YAHOO.util.Connect.asyncRequest('POST', elTarget.href, $GP.delDestCallback); 
				passThru = false;				
			} else {

				$GP.loadPanel(target, extraArgs);
				passThru = false;				
			}

		break;

		case(command == 'close_panel'):

			$GP.thePanel.hide();
			passThru = false;
		break;
		
		case(command == 'showmap'):

			passThru = false;

			window.scroll(0,$D.getY('map'));
			$GMmap.showMarker(target);

		break;

		//Logged in, tries to add to passport
		//or delete passport.
		case(command == 'hidemarker'):

			passThru = false;

			$GMmap.removeMarker(target);

		break;
		
		case(command == 'logout'):
			YAHOO.util.Connect.resetFormState();
			var request = YAHOO.util.Connect.asyncRequest('POST', 'action/sitelogout', $GP.submitHandlerCallback); 
			passThru = false;
		break;

		//Play audio flash files
		case(command == 'playaudio'):
		
			passThru = false;
			$GP.playAudio(elTarget);
			
//			if(!$L.isUndefined(deconcept) && (deconcept.SWFObjectUtil.getPlayerVersion().major <= 9) ) {
			// if( true ) {
			// 	passThru = false;
			// 	$GP.playAudio(elTarget);
			// } else {
			// 	elTarget.target = "_blank";
			// }

		break;

		//Send email
		case(command == 'mailto'):
			window.open("mailto:"+target+"@girlports.com", "_self");
			passThru = false;
		break;

		//Slide ad div
		//This is specific to one case. Can be more generalized if needed.
		case(command == 'slide'):
			//Since we openthe slidy ad on page load, and set a time out to autohide it, 
			//we now check if that timeout is set. If it is, we cancel it, since the user has taken manual control.
			if($GP.getFlag('slideAdTimeoutId')){
				clearTimeout($GP.getFlag('slideAdTimeoutId'));
				//and reset it to false;
				$GP.setFlag('slideAdTimeoutId', false);
			}

			passThru = false;
			var toAnim = $D.get(target);
			$GP.slideAdDiv(toAnim);
		break;
		
		case(command=='view_my_passport'):
			// @BBUG Seems when you overwrite the el that actually called the event, 
			//IE7 doesnt like it, and wont continue the action, so will force the action.
			var linkTarget = elTarget.href;
			$DH.overwrite(elTarget.parentNode, '<span class="loading"><img style="margin-left: 20px; vertical-align: text-top;" src="_images/common/ajax-small-flower.gif" /> Loading...</span>');
			location.href = linkTarget;
		break;
		case(command=='view_listings'):
			// @BBUG Seems when you overwrite the el that actually called the event, 
			//IE7 doesnt like it, and wont continue the action, so will force the action.
			//Repeat of above, to deal with diff style.
			var linkTarget = elTarget.href;
			$DH.overwrite(elTarget.parentNode, '<span class="loading"><img style="vertical-align: text-top;" src="_images/common/ajax-small-flower.gif" /> Loading...</span>');

			location.href = linkTarget;
		break;
	}

	if( false == passThru ){
		YAHOO.log('stopping link event');
		$E.stopEvent(e);
	}	
};


$GP.submitHandler = function(e) {

	var formAction = $E.getTarget(e).action;
	var form = $E.getTarget(e);
	var formId = form.id;
	var callbackHandler = $GP.submitHandlerCallback;
	var extraArgs;

	//Some forms, we dont want to handle
	switch(true){
		case(formId.indexOf('searchbox') > -1):
		case(formId == 'form_contact'):
		case(formId == 'form_profile_information'):
		case(formId == 'confirm_email_form'):
			//Submission, so we want to null out the beforeunload handler
			window.onbeforeunload = null;
			return;
		break;
	}

	$E.stopEvent(e);

	var reqform = YAHOO.util.Connect.setForm( formId );
	
	//Let the callback function know what the form id is
	callbackHandler.argument = {"form": form };
	
	switch(true) {
		//User not logged in, tries to add to passport.
		case ( (GpIsLoggedIn == false) && ( formId.indexOf('add_to_passport') > -1) ):

			$GP.loadPanel('nopassport');
			return;
		break;
		case(formId.indexOf('delete_from_passport_formc') > -1):
			//for delete from my passport_wrapper
			var swapOld = form.safari_comp.value;
			var buttonName = 'but-panel-confirm_delete-'+form['data[listing_id]'].value+'-'+form['data[marker_id]'].value;
			
			YAHOO.util.Connect.startEvent.subscribe($GP.loadingIcon.small, {'responseEl': buttonName });
			callbackHandler = $GP.confirmDeleteCallback;
			
		break;	
		case((formId.indexOf('delete_from_passport_form') > -1) || (formId.indexOf('add_to_passport') > -1)):
			//for destinations page, 
			
			callbackHandler = $GP.PassportCallback;
			//Using safari comp value, since that represents the value we need - add or delete from passport
			var swapOld = form.safari_comp.value;
			var swapNew = (swapOld == 'add_to_passport') ? 'delete_from_passport' : 'add_to_passport'; 
						
			var buttonName = "but-"+swapOld+"-"+form['data[listing_id]'].value;
			extraArgs = "swapOld="+swapOld+"&swapNew="+swapNew;
			
			//Animate the button
			var oldButton = $D.get(buttonName);
			var toAnim = oldButton.firstChild.cloneNode(true);

			document.body.appendChild(toAnim);
			$D.setXY(toAnim, $D.getXY(oldButton));
			//Set Animate attribs
			//relative point to work from
			var rpoint = $D.getXY(toAnim);

			//Default - Add
			var xy_anim = [rpoint[0] + 235, rpoint[1] + -100]; 
			var points = { to: xy_anim, control: [  [rpoint[0] + 300, rpoint[1] + 100] ] } ;
			//Other Options
			if(swapOld == 'delete_from_passport') {
				xy_anim = [rpoint[0], rpoint[1]+150];	
				points = { to: xy_anim} ;
			}

		//	YAHOO.util.Connect.startEvent.subscribe($GP.loadingIcon.small, {'responseEl': buttonName });

			
			var motionAttribs = { points:  points };
			var animAttribs = {opacity: { to: 0 } };
			$GP.animate (toAnim, motionAttribs, animAttribs);			
			
		break;
		default:
	}
	
	

	//This will be infered by default if not set - will be id-wrapper. Can be overridden in the php reply.
	//var extraArgs = "data[responseEl]="+parentNodeId;
	var request = YAHOO.util.Connect.asyncRequest('POST', formAction, callbackHandler,extraArgs);	
	

};

/**
*Grab all forms on page, apply submit listeners
*Doing this since submit doesnt seem to bubble beyond the forms on Safari/IE7
*which seems weird
*/
$GP.initSubmitListener = function() {

	//collect all forms on the page:
	var forms = document.getElementsByTagName('form');

	//Remove all listeners that may already be attached
	//we do this because when we load a new form to display via ajax
	//we will have to reinit the listeners, so we should remove all that may already
	//be attached if there is more than one form on the page
	$E.removeListener(forms, 'submit');
	
	//Then attach new listeners
	$E.addListener(forms, 'submit', $GP.submitHandler);

	//Quick exclusion for the google search box

	$E.removeListener($D.get('searchbox_015293228986176785549:hbmu0otzeey'),'submit');

	$GP.inputInit();

};

$GP.formReset = function(form) {

	//get the original values
	//reset the form values.
	var els = form.elements;

	for (var i=0; i < els.length; i++) {
		if( els[i].type == 'text' || els[i].type == 'textarea' ) {
			var formIdentifier = els[i].form.id+'_'+els[i].name;
			els[i].value =  $GP.getFlag('originalInputVals')[formIdentifier];
		}
	}
	
};

/*
 * Handles managing default values for forms. form inputs managed if they have a class of inputHandler
 * will empty a field on focus, and refill with default if there's no change.
 * Will check ID of input to see if word password is found - if so, assume its a PW field, and switch it accordingly
 *
 * Rules: 
 *	Password fields need work password in ID
 *	Class name of inputHandler on element
 * @type string
 */
$GP.inputHandler = function(e) {

	var elTarget = $E.getTarget(e);

	var formIdentifier = elTarget.form.id+'_'+elTarget.name;//elTarget.form.id;

	switch(e.type.toLowerCase()) {
		
		case('focus'):
			if( $GP.getFlag('originalInputVals')[formIdentifier] == elTarget.value) {
				elTarget.value = '';
			}
			$D.removeClass(elTarget, 'blur');
			$D.addClass(elTarget, 'focus');
		break;
		case('blur'):
			if($L.trim(elTarget.value) == ''){
				if(elTarget.id.indexOf('password') == -1){
					elTarget.value =  $GP.getFlag('originalInputVals')[formIdentifier];
				}
			}
			$D.removeClass(elTarget, 'focus');
			$D.addClass(elTarget, 'blur');
			
		break;
		default:
		 //nothing yet.
	}
			
};



/*
*Initialize all inputs on the page to use the input handler. 
*Called from initSubmit Listener,since that gets called whenever we load a form
*/
$GP.inputInit = function(){

		//Input Blur/Focus events don't bubble, so we target them specifically to any input element with inputHandler class.
		var formInputs = $D.getElementsByClassName('inputHandler', 'input');
		formInputs=formInputs.concat($D.getElementsByClassName('inputHandler', 'textarea') );

		var origVals = {};
		//Store the original input values
		$D.batch(formInputs, function(el){
			var formIdentifier = el.form.id+'_'+el.name;
			origVals[formIdentifier] = el.value;

		});
		
		$GP.setFlag('originalInputVals',origVals);	
		
		$E.removeListener(formInputs, "blur");
		$E.removeListener(formInputs, "focus");
		
		$E.addListener(formInputs, "blur", $GP.inputHandler);
		$E.addListener(formInputs, "focus", $GP.inputHandler);
};

/**
 *	Handles init of the slide out ad, when someone lands on page for first time. 
 *  Dislplays, and sets timeout for hide.
**/
$GP.initSlidyAd = function () {
	
	//Sanity check, in case this goes live before the banner is live.
	//Also, chec if we are not on the home page, dont do the slidy.
	if( (!$D.get('top_banner')) || (document.body.id != 'home')) {
		return;
	}
	//Slide out the slidy ad div.
	//Expect Top Banner to be id="top_banner"
	$GP.slideAdDiv($D.get('top_banner'));

	//Set the time out, and set the ID in the flag, so we can cancel it on user override
  $GP.setFlag('slideAdTimeoutId', setTimeout("$GP.slideAdDiv($D.get('top_banner'))",5000));

};

/*
 * Looks for any elements with class=flashme, and flashes them.
 * Currently only for the h3 on the quick register form, so very specific
 */
$GP.flashMe = function() {
	$D.batch(
		$D.getElementsByClassName('flashme', 'h3'),
		$GP.flash(el)
	);
};

$GP.flash = function(el) {
 	var anim = new YAHOO.util.ColorAnim(el, {backgroundColor: {to: '#ff6d00'}, color: {to:'#fff'}}, 1, YAHOO.util.Easing.easeIn);
	anim.animate(); 
};

/*
 * Init function for GP. Fires on DOMReady
 */
$GP.init =  function () {
	YAHOO.log("Init");
	//Safari & IE7 - Submit listeners have to be applied directly to forms - dont bubble up.
	//Firefox - they bubble. WTF?!
	$GP.initSubmitListener();	
	$E.on('container-fullwidth', "click", $GP.clickHandler); 
	$E.on('container-fullwidth', "mouseover", $GP.rollover);
	$E.on('container-fullwidth', "mouseout", $GP.rollover);
	//$GP.centerCoords();
	$GP.initSlidyAd();
	$GP.flashMe();
};

/*
 * Load $GP script once the DOM is ready
 */
YAHOO.util.Event.onDOMReady($GP.init, {}, $GP);

/*
 * Image Preloader
 *
 * Using it to preload the ajax flower, but can add anything. 
 */
var $GPLoader = YAHOO.namespace('GirlPorts.ImageLoader');

$GPLoader = function () {

	var $D = 	YAHOO.util.Dom;
	var $E = 	YAHOO.util.Event;
		
	return {

		/*
		 * Init function
		 */
		init: function () {
			var ajax_flower_small = new Image();
			ajax_flower_small.src = '_images/common/ajax-small-flower.gif';
		}
		
	};
	
} ();
YAHOO.util.Event.onDOMReady($GPLoader.init);