// JavaScript Document


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function closeWindow()
{   
	if (self.open) self.close();
}

/*** Could not find reference to this function anywhere in the code - DEPRECATED
function toggleDiv(divid){
    if(document.getElementById(divid).style.display == 'none'){
      document.getElementById(divid).style.display = 'block';
    }else{
      document.getElementById(divid).style.display = 'none';
    }
}
***/
 
/**
 * This function is used to clear the red error designation on form fields
 */
function clearError( field )
{
	$( field ).addClassName ( 'formField' );
	$( field ).removeClassName ( 'validationFailed' );
	$( 'err_' + field ).innerHTML = "";
}

/**
 * This function is used to clear the red error designation on message fields
 */
function clearError2( field )
{
	$( field ).addClassName ( 'formTextArea' );
	$( field ).removeClassName ( 'validationFailed' );
	$( 'err_' + field ).innerHTML = "";
}

/**
 * This function is used to clear the red error designation on form fields in admin
 */
function clearErrorAdmin( field )
{
	$( field ).removeClassName ( 'validationFailed' );
	$( 'err_' + field ).innerHTML = "";
}

/**
 * Clears the error class and error message and adds the class you provided
 */
function clearErrorAddClass( el_id, el_class )
{
	$( el_id ).removeClassName ( 'validationFailed' );
	$( el_id ).addClassName ( el_class );
	$( 'err_' + el_id ).innerHTML = ""; 
}

/** 
 * Our Venngo customized LightWindow pop-up function (lightwindow_venngo.js) 
 */ 
var lightWindowVenngoPopup = function (url, /* optional */ title_caption, width, height, window_type, top, left, caption, author, rel, showImages, loadingAnimation, iframeEmbed)
{
	var options = {
		href : url,										/* Values:	(string)	A valid URL for the window and it can determine if the URL is a site, image or media */
		title : title_caption || null,					/* Values:	(string)	The title of the window */
		width : width || null,							/* Values:	(integer)	The width of the window */
		height : height || null,						/* Values:	(integer)	The height of the window */
		type : window_type || null,						/* Values:	(string)	The type of the window you want to change it too: image, page, media, inline, external */
		top : top || null,								/* Values:	(integer)	Top position of the window */
		left : left || null,							/* Values:	(integer)	Left position of the window */
		caption : caption || null,						/* Values:	(string)	The caption of the window */
		author : author || null,						/* Values:	(string)	The author of the window */
		rel : rel || null,								/* Values:	(string)	Set the rel tag */
		showImages : showImages || null,				/* Values:	(integer)	How many images to show */
		loadingAnimation : loadingAnimation || null,	/* Values:	(boolean)	Make the loading cover skip the animation */
		iframeEmbed : iframeEmbed || null				/* Values:	(boolean)	Emebed the Media into an iframe instead of a div form */
	};
	
	// Activate/Open venngoLightWindow
	venngoLightWindow.activateWindow( options );
}

function roundTo( theNumber, digits )
{
	return ( Math.round( Math.pow( 10, digits ) * theNumber ) / Math.pow( 10, digits ) );
}

function removeChars( value )
{
	return value.replace(/[\W]/gi, '');
}

/**
 * A 'Singleton' HTML object
 */
var HTML = 
{
	/**
	 * Validate our email address (uses Prototype Library)
	 */
	emailValidate : function ( email_address )
	{
		if ( email_address == null )
		{
			return false;
		}
		
		var email = email_address.strip();
		
		if (email_address.length==0)
		{
			return false;
		}
		
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
		// Two periods in a row is not valid
		if ( email.indexOf("..") >=0 )
		{
			return false;
		}
		
		// Check against our regular expression for valid email
		if ( reg.test(email) == false )
		{
			return false;
		}
		
		return true;
	},
	
	/**
	 * Capture our stat and pop-up print dialog box
	 */
	printPerkCaptureStat : function ( perk_id, capture_url )
	{
		// Capture our pop-up print dialog stats
		ajaxRequest( capture_url, 'perk_id='+perk_id+'&useNav=false', null, null, "post" );
		
		// Now pop-up our system print dialog box
		window.print();
	},
	
	/**
	 * This will fire up an event for our search element
	 */
	executeSearch : function ( elementID )
	{
		// Fire our custom event for our search element 
		$(elementID).fire("customEvent:executeSearch");
	},
	
	/** 
	 * This function uses Prototype String functions 
	 */
	secureInput : function ( inputValue )
	{
		// Assuming inputValue is a Prototype string object
		var inputV = inputValue;
		
		inputV = inputV.strip();
		inputV = inputV.stripScripts();
		inputV = inputV.stripTags();
		inputV = inputV.escapeHTML();
		
		return inputV;
	},
	
	/**
	 * This function returns our browser type
	 */
	getBrowserAgent : function ()
	{
		var ua = navigator.userAgent.toLowerCase();
		
		if (ua.indexOf("opera") != -1)
		{
			return "opera";
		}
		else if (ua.indexOf("safari") != -1)
		{
			return "safari";
		}
		else if (ua.indexOf("msie 6") != -1)
		{
			return "ie6"; 
		}
		else if (ua.indexOf("msie 7") != -1)
		{
			return "ie7";
		}
		else if (ua.indexOf("mozilla") != -1)
		{
			var geckoIdx = ua.indexOf("gecko/");
			if (geckoIdx == -1) return "oldmoz";
			
			var spaceIdx = ua.indexOf(" ", geckoIdx);
			if (spaceIdx == -1) spaceIdx = ua.length;
			
			// Firefox1.5's Gecko version
			var version = parseInt(ua.substring(geckoIdx + 6, spaceIdx));
			if (version < 20051107) return "oldmoz";
			
			return "moz";
		}
		
		return "unknown";
	},
	
	/**
	 * This function grows the rows of a text area box
	 */ 
	resizeTextArea : function ( txtBox_obj )
	{ 
		cols = txtBox_obj.cols;
		textValue = txtBox_obj.value;
		textValueLength = textValue.length;
		rowCount = 1;
		
		for ( i=0; i < textValueLength; i++ )
		{
			// Check for newline characters
			if ( (textValue.charAt(i).charCodeAt(0) == 10) || (textValue.charAt(i).charCodeAt(0) == 13) )
			{
				rowCount +=1;
			}
		} 
		
		if (rowCount < (textValueLength / cols))
		{
			rowCount = 1 + (textValueLength / cols);
		}
		
		txtBox_obj.rows = rowCount;
		
		//--- DEBUGGING
		//alert('cols: '+cols+'\ntextValue: '+textValue+'\ntextValueLength: '+textValueLength+'\nrowCount: '+rowCount);
	},
	
	/**
	 * Disable/Enable a form field and remove the value
	 */
	disableEnableField : function ( fieldID )
	{
		$(fieldID).value = "";
		
		if ( $(fieldID).disabled == true ) $(fieldID).disabled = false;
		else $(fieldID).disabled = true;
	},
	
	/**
	 * Clear Error Messages
	 */
	clearErrorMessage : function ( fieldName )
	{
		$(fieldName).innerHTML = '';
	},
	
	/**
	 * Show / Hide Element via ID
	 */
	showHideElement : function ( elementID )
	{
		if ( $(elementID).style.display == 'none' ) Effect.Appear(elementID,{duration:0.1});
		else Effect.Fade(elementID,{duration:0.1});;
	},
	
	/**
	 * This function gets parameters from the URL.
	 * E.g. If you have a URL like so, http://www.abc.com/index.html?marko=123&polo=abc&mario=xxxxx#top
	 * and you want to get the value of the 'polo' parameter so 
	 * you call it like so: var polo_param = HTML.getURLParam('polo');
	 */
	getURLParam : function ( paramName )
	{
		paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		
		var regexS = "[\\?&]"+paramName+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		
		if( results == null ) return "";
		else return results[1];
	},
	
	/**
	 * This function converts a string into a date
	 *
	 * str formats supported:
	 *    MM-dd-yyyy       -> 03-20-2009
	 *    yyyy/MM/dd       -> 2009/03/20
	 *    MM/dd/yyyy       -> 03/20/2009
	 *    MMMM dd, yyyy    -> March 20, 2009
	 *    MMM dd, yyyy     -> Mar 20, 2009
	 *    yyyy-MM-dd       -> 2008-03-20
	 *
	 * Reference to JS Date Functions: http://www.w3schools.com/jsref/jsref_obj_date.asp
	 */
	stringToDate : function ( str )
	{
		var newDate = new Date( str );
		
		if ( (newDate == 'Invalid Date') || (newDate == 'NaN') )
		{
			var date = str.split("-");
			
			// NOTE: setFullYear(year, month, day) - The months go from 0-11, not 1-12.
			newDate = new Date();
			newDate.setFullYear(Math.abs(date[0]), Math.abs(date[1])-1, Math.abs(date[2]));
		}
		
		return newDate;
	}
};

/**
 * Our VENNGO_SEARCH class
 */
function VENNGO_SEARCH( elementID, searchCategoryID, searchURL, alertMsg, searchStyleBG ) 
{
	this.searchElementID = elementID;
	this.searchCategoryID = searchCategoryID;
	this.searchURL = searchURL;
	this.searchAlertMsg = alertMsg;
	this.searchStyleBG = searchStyleBG;
	
	/**
	 * This function will give us the values our vars
	 */
	this._debug = function ( )
	{
		alert ( 
			'searchElementID: ' + this.searchElementID + '\n\n' + 
			'searchCategoryID: ' + this.searchCategoryID + '\n\n' + 
			'searchURL: ' + this.searchURL + '\n\n' + 
			'searchAlertMsg: ' + this.searchAlertMsg + '\n\n' + 
			'searchStyleBG: ' + this.searchStyleBG + '\n\n' + 
			'Search URL: ' + this.searchURL + "&keyword=" +  $(this.searchElementID).value + "&category_id=" + $(this.searchCategoryID).value
		);
	}
	
	/**
	 * This function adds event listeners to our search box with a message
	 */
	this.addSearchBoxEvent = function ( )
	{
		// Check for data in searchElementID
		if ( ! $(this.searchElementID).value.blank() )
		{
			// Has data, so clear style
			$(this.searchElementID).style.background = '';
		}
		
		// Capture 'Native' Events
		$(this.searchElementID).observe('click', this.executeSearchBoxInput.bind(this));
		$(this.searchElementID).observe('blur', this.executeSearchBoxInput.bind(this));
		$(this.searchElementID).observe('keypress', this.executeSearchBoxInput.bind(this));
		
		// Capture our 'Custom' Events, wrapped in namespace 'customEvent'
		$(this.searchElementID).observe('customEvent:executeSearch', this.executeSearchBoxInput.bind(this));
		
		//this._debug();
	}
	
	/**
	 * This function executes our search request
	 */
	this.executeSearchBoxInput = function ( event )
	{
		// If enter key is pressed OR 
		// custom event is executed OR 
		// native event 'blur' is executed
		if (	( (event.keyCode != undefined) && (event.keyCode == 13) ) || 
				( (event.type == 'dataavailable') && (event.eventName=='customEvent:executeSearch') ) || 
				( (event.type == 'blur') )
		)
		{
			// Validate our input value
			$(this.searchElementID).value = this.validateSearchBoxInput( $(this.searchElementID) );
			
			// If value is blank
			if ( $(this.searchElementID).value.blank() )
			{
				// Add our style background
				$(this.searchElementID).style.background = this.searchStyleBG;
				
				// If enter key is pressed OR custom event is executed, show message
				if (	( (event.keyCode != undefined) && (event.keyCode == 13) ) || 
						( (event.type == 'dataavailable') && (event.eventName=='customEvent:executeSearch') ) 
				)
				{ 
					//--- DEBUGGING
					//this._debug();
					
					alert( this.searchAlertMsg );
				}
			}
			// If just moving away from the element
			else if ( event.type == 'blur' )
			{
				// Do nothing...
			}
			// If less than or equal to 2 characters
			else if ( $(this.searchElementID).value.length <= 2 )
			{
				alert( this.searchAlertMsg );
			}
			else
			{
				var documentProtocol = document.location.protocol;
				var documentHost = document.location.host;
				
				// If we have http or https then...
				if ( searchURL.match("http") != null )
				{
					var redirect_location = this.searchURL + "&keyword=" +  $(this.searchElementID).value + "&category_id=" + $(this.searchCategoryID).value;
				}
				else
				{
					var redirect_location = documentProtocol + '//' + documentHost + this.searchURL + "&keyword=" +  $(this.searchElementID).value + "&category_id=" + $(this.searchCategoryID).value;
				}
				
				//--- DEBUGGING
				//this._debug();
				//alert( 'SEARCH NOW\n\n'+ redirect_location );
				//window.location.href
				//window.location.replace( redirect_location );
				
				setTimeout( function()
				{
					window.location.href = redirect_location;
				}, 0);
			}
		} // End of if...
		else
		{
			// Remove our style background
			$(this.searchElementID).style.background = '';
		}
		
		//--- DEBUGGING
		/**
		switch ( event.type )
		{
			// Custom Events
			case 'dataavailable':
				// executeSearch event is called
				if (event.eventName=='customEvent:executeSearch') alert( event.eventName );
				break;
				
			// Native Events
			case 'click':
			case 'keypress':
			case 'blur':
				alert( event.type )
				break;
		} // End of switch...
		**/
	}
	
	/**
	 * This function validates our search box input
	 */
	this.validateSearchBoxInput = function( elementID )
	{
		elementID.value = elementID.value.strip();
		
		return elementID.getValue();
	}
		
} // End of VENNGO_SEARCH...

/**
 * Prototype version of NL2BR on PHP
 *
 * Usage: 
 *    var myString = document.getElementById( 'textarea' );
 *    var brString = myString.nl2br();
 *    var brString = myString.nl2br( '<br>' ); // Specify the tag you want to use as a new line ender
 */
String.prototype.nl2br = function()
{
	var br;
	
	if ( typeof arguments[0] != 'undefined' )
	{
		br = arguments[0];
	}
	else
	{
		br = '<br />';
	}
	
	return this.replace(/\r\n|\r|\n/g, br);
}


/**
 * Prototype version of BR2NL on PHP
 */
String.prototype.br2nl = function()
{
	var nl;
	
	if ( typeof arguments[0] != 'undefined' )
	{
		nl = arguments[0];
	} 
	else
	{
		nl = '\r\n';
	}
	
	return this.replace(/\<br(\s*\/|)\>/g, nl);
}
