// JavaScript Document

// Imediatly exicuted functions (before the dom has finished loading)
(function() {
		  
		/** IE FIX, adds the border radius to ie browsers */
		roundMyCorners();
		
		// Check if Text only version is enabled? 
	    if(readCookie('textOnlyVersionEnabled')=='True') textOnlyVersion();
})();

// if ie6 this will become true, otherwise it will remain undefined/false
var isRunningIE6OrBelow;

// Run the following as soon as page has loaded 	(as soon as the dom has loaded)
document.observe("dom:loaded", function() {
				
		// $('ajax_result').ajaxify('ajax/request'); 
				
		/// Fix the menu css (adds menu arrows) 
		menuFix();	
			
		// IE Fixes
		if(detectIEBrowser()) {  
			addPixels('.header-inner', '4', 'width'); 	
			addPixels('.middle-inner', '4', 'width'); 	
			addPixels('.footer-inner', '4', 'width'); 	
		} 
		
		// Fix anchor links/hash values (base href issue)  
		fixForHashLinks();
		
		// Init Lightbox
		//if(typeof initLightbox == Array()) initLightbox();
		
		// Assign Text Only Version Link
		$j('#text_only_version').click(function() {
			
			textOnlyVersion(this); return false;
		});
		
});

// As user exists the page, perform the follwing functions...  
window.onunload = function() {
	
	//alert('exiting page'); 
}

// fix the hash anchor links 
function fixForHashLinks() {
		
		// Hash/Anchor ammendment so all hash/anchor links will have a nice scroll to the element     
		$j("a[href^='\#']").click(function(e){
		  e.preventDefault();
		  var hashValue = this.href.substr(this.href.indexOf('#')); 
		  var hashId = hashValue.replace('#','');
		  if( hashId && (hashId!='') && $(hashId) ) {
			
			Effect.ScrollTo(hashId, { duration: 0.8 });
			timeDelay(function() { document.location.hash = hashValue; }, 800); 
		  }
		  else {
		  	document.location.hash = hashValue;			  
		  }		  
		});
}

// Monitor all key presses via the following function
function keyPressHandler(e) {
     
	 // Key Code Pressed
	 var keyPressed	= (window.event) ? event.keyCode : e.keyCode; // MSIE : Firefox
     
	 // Key Code Values 
	 var EscKey 	= (window.event) ? 27 : e.DOM_VK_ESCAPE; 
     var EnterKey 	= (window.event) ? 13 : e.DOM_VK_ENTER; 
     var ReturnKey 	= (window.event) ? 13 : e.DOM_VK_RETURN; // Firefox uses a different key for return and enter 
	  if(ReturnKey) EnterKey = ReturnKey; 
	 
	       	 
	 switch (keyPressed) { 	
		 // if the key pressed is the ESC key 	
		case EscKey: escKeyFunctions(); break;
	 	// if the key pressed is the ENTER key  
		case EnterKey: enterKeyFunctions(); break;
	}
     
}

// On press of the ESC key 
function escKeyFunctions() { 
	
	// if the modal demo is alive and open, then close it 
	if(modal && modal.isOpen()) modal.close();
	// if the modal cart is alive and open, then close it 
	if(cart && cart.isOpen()) cart.close(); 
}

// On press of the ENTER key 
function enterKeyFunctions() { 

	//alert('Enter Key Clicked!');
}

var modal;
function openModalDemo() {
		
	// Init New Modal Window
	modal = new ModalWindow({
		title	 	: 'Modal Title Here',
		content	 	: '<div class="modal_slide_top"> \
						<div class="main"> \
						 <h1>Content Here</h1> \
						 <p>Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p> \
						</div> \
						<a class="modal_close" onclick="modal.close();">close</a> \
					   </div>',
		scrollTo 	: true,
		closeAfter	: 4000
	});
}

var cart;
function openModalCart() {
	
	var cartContent;
	cartContent  = '<div class="modal_cart">';
	cartContent += '<a class="modal_close" onclick="cart.close();">close</a>';
	cartContent += '<h1> My Cart </h1>';
	cartContent += '<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>';
	cartContent += '</div>';
		
	// Init New Modal Window
	cart = new ModalWindow({
		title	 	: 'Modal Cart',
		content	 	: cartContent,
		position	: 'fixed',
		closeAfter	: 4000
	});
}

// Add Pixels To An Elements Size 
var objId, amtAdd, addToPart;
function addPixels(objId, amtAdd, addToPart) {
	var newWIdth = (parseInt($j(objId).css(addToPart).replace("px",''))+parseInt(amtAdd)) + "px";
	$j(objId).css(addToPart, newWIdth);
}

// Retur A Random Number 
function randomNum() {
	return Math.floor(Math.random()*10);
}

// ADDED ELEMENT METHOD FOR AJAXing an element 
Element.addMethods({
	ajaxme: function(element, url, addedObj) { 
		if(!element.id) element.id = "ajaxify_"+randomNum();
		AjaxRequest(url, 'GET', element.id);
	}
});

// Pre defined setup for a simple ajax request 
var url, method, loadingBoxID, completeBoxID, loadingMessage, failedMessage, addedParams;
function AjaxRequest(url, method, loadingBoxID, completeBoxID, loadingMessage, failedMessage, addedParams) {
		
	if(url==undefined) 	alert('No url set for ajax request!'); // Method of request GET/POST
	
	// Default Defined Variables 
	if(method==undefined)				method 			= 'GET';			// Method of request GET/POST
	if(loadingBoxID==undefined) 		loadingBoxID 	= 'ajax_result'; 	// Loading text div id 
	if(completeBoxID==undefined)		completeBoxID 	= loadingBoxID; 	// Compelted/failed text div id 
	if(loadingMessage==undefined)		loadingMessage	= 'Loading...';		// Default loading message  
	if(failedMessage==undefined)		failedMessage	= 'Sorry but the request failed, please try again';		// Default loading message  
	
	if(addedParams==undefined) 			addedParams		= {}; 	// additional parameters 
		
	new Ajax.Request(url,
	  {
		method: method,
		parameters: addedParams,	
		onLoading: function() {
			if($(loadingBoxID)) $(loadingBoxID).innerHTML = loadingMessage;			
		},
		onSuccess: function(transport){
			timeDelay(function(){ // add a tiny time delay so no errors to avoid loading too quick 
				var response = transport.responseText || "no response text";
				if($(completeBoxID)) $(completeBoxID).innerHTML = response;			
			});
		},
		onFailure: function(){ 
			timeDelay(function(){ // add a tiny time delay so no errors to avoid loading too quick 
				if($(completeBoxID)) $(completeBoxID).innerHTML = failedMessage;						   
			});
		}
	  });
}

// Simple time delay 
function timeDelay(theFunction, timeAmt) { 
	if((timeAmt==undefined)||(timeAmt=='')) timeAmt = 100;	// Default Time Amount  
	return setTimeout(theFunction, timeAmt); 
}


// Simple repeat with delay 
function repeatDelay(theFunction, timeAmt) { 
	if((timeAmt==undefined)||(timeAmt=='')) timeAmt = 100;	// Default Time Amount  
	return setInterval(theFunction, timeAmt); 
}

// IE Rounded Corners Fix with DD_roundies to the bellow marked css classes
function roundMyCorners() {

	DD_roundies.addRule('.round-top', '6px 6px 0px 0px');
	DD_roundies.addRule('.round-bottom', '0px 0px 6px 6px');
	DD_roundies.addRule('.round-small', '4px');
	DD_roundies.addRule('.round-medium', '8px');
	DD_roundies.addRule('.round-large', '14px');
	//DD_roundies.addRule('.round-large', '14px', true);	
}

// Detect IE Browser
function detectIEBrowser() {
	
	var agent= navigator.userAgent.toLowerCase();		 
	var ie = agent.indexOf("msie")>=0;
	//var b_version = navigator.appVersion;
	//var version = (b_version.indexOf("msie "+versionNum)) ? true : false;
	
	return ie;
	//if(ie) return version;
	//else return false;
		
}

// Menu Fix
function menuFix() {
	
	// menu header fix  (for ie5 and 6 )
	$$('ul.header-menu li').each(function(eS){
		
		// if list item contains another list(ul) element then add a class of 'containsSub'
		//  and mouseOver and Off effects to hide and show the menu 
				
		var insideLiItem = eS.innerHTML.toLowerCase();
				
		if( insideLiItem.search('<ul>') != -1 ) {
					
			eS.addClassName('containsSub');	
			
			//eS.onmouseout = function() { 		
				// this 
			//}; 
			
			//eS.onmouseover = function() { 		
				// this 
			//};
			
		}
			
	});	
}

/** 
 * Cookie Functions, 
 *  - to make use of cookies much easier like in php, 
 */
// Get Cookie 
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
// Set Cookie 
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}
// Delete Cookie 
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}



/**
 * The following adds a posible extension for alerts
 *  basicly all alerts remain the same, and always do on old browsers,  
 *  but on new browsers you can add an aded param to make the aleert work through the modal window class
 *  @usage: alert('hello');		  	-> old method, still works
 * 			alert('hello', true); 	-> new method, modal window version
 *
 *  @extra: if you want it to work the other way arround and you have to add the extra param for the old version and all current alerts to work with the modal class, just change the var malwaysOverrideAlerts to true
 *
 */
var txt;
var alwaysOverrideAlerts = false; // modal the alerts by default true or false (first place)
var modalOrNotAlerts;
var titleText;
// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts 
if(document.getElementById) {
	var oldAlert = window.alert;
	window.alert = function(txt, modalOrNotAlerts) {
		createCustomAlert(txt, modalOrNotAlerts);
	}
}
function createCustomAlert(txt, modalOrNotAlerts, titleText) {
			
	if(!titleText) titleText = "Alert!";
	if(modalOrNotAlerts || alwaysOverrideAlerts) {
		var alertContent;
		alertContent  = '<div class="modal_alert">';
		alertContent += '<a class="modal_close" onclick="newAlert.close();">close</a>';
		alertContent += '<h1> '+ titleText +' </h1>';
		alertContent += '<p>'+ txt +'</p>';
		alertContent += '</div>';
			
		// Init New Modal Window
		newAlert = new ModalWindow({
			title	 	: titleText,
			content	 	: alertContent,
			position	: 'fixed',
			closeAfter	: 4000
		});
	}
	else {
		oldAlert(txt);
	}
}

  // Text only version of site, without any CSS, switch on or off 
  var onOrOff = 'on';
  var objEl;
  function textOnlyVersion(objEl) {
	  
	  // Loop all stylesheets, to disable them 
	  $j("link[rel='stylesheet']").each(function() {
		  if(onOrOff == 'on') $j(this).attr('disabled', 'true');
		  else $j(this).removeAttr('disabled')
	  });
	  
	  // Loop all stylesheets, to disable them 
	  $j("img").each(function() {
		  if(onOrOff == 'on') $j(this).hide();
		  else $j(this).show();
	  });
	  
	  // set the onOrOff var 
	  if(onOrOff == 'on') {
		  onOrOff = 'off';
		  if(objEl!=undefined) objEl.innerHTML = 'Text Only Version';
		  
		  // Set cookie for text-only mode to be on 
		  newCookie('textOnlyVersionEnabled', 'True');
	  }
	  else {
		  onOrOff = 'on';
		 if(objEl!=undefined)  objEl.innerHTML = 'View Full Version';
		  
		  // Remove cookie for text-only mode to be on 
		  eraseCookie('textOnlyVersionEnabled'); 
	  }
	  
  }
  
  
function newCookie(name,value,days) {
 var days = 1;   // the number at the left reflects the number of days for the cookie to last
                 // modify it according to your needs
 if (days) {
   var date = new Date();
   date.setTime(date.getTime()+(days*24*60*60*1000));
   var expires = "; expires="+date.toGMTString(); }
   else var expires = "";
   document.cookie = name+"="+value+expires+"; path=/"; 
}

function readCookie(name) {
   var nameSG = name + "=";
   var nuller = '';
  if (document.cookie.indexOf(nameSG) == -1)
    return nuller;

   var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameSG) == 0) return c.substring(nameSG.length,c.length); }
    return null; 
}

function eraseCookie(name) {
  newCookie(name,"",1); 
}

