/**
 * Copy the value of an input field's title attribute to its value attribute.
 * Clear the input field on focus if its value is the same as its title.
 * Repopulate the input field on blur if it is empty.
 * Hide the input field's associated label if it has one.
 */
var autoPopulate = {
	sInputClass:'populate', // Class name for input elements to autopopulate
	sHiddenClass:'structural', // Class name that gets assigned to hidden label elements
	bHideLabels:true, // If true, labels are hidden
	/**
	 * Main function
	 */
	init:function() {
		// Check for DOM support
		if (!document.getElementById || !document.createTextNode) {return;}
		// Find all input elements with the given className
		var arrInputs = autoPopulate.getElementsByClassName(document, 'input', autoPopulate.sInputClass);
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			// Make sure it's a text input
			if (oInput.type != 'text') { continue; }
			// Hide the input's label
			if (autoPopulate.bHideLabels) { autoPopulate.hideLabel(oInput.id); }
			// If value is empty and title is not, assign title to value
			if ((oInput.value == '') && (oInput.title != '')) { oInput.value = oInput.title; }
			// Add event handlers for focus and blur
			autoPopulate.addEvent(oInput, 'focus', function() {
				// If value and title are equal on focus, clear value
				if (this.value == this.title) {
					this.value = '';
					this.select(); // Make input caret visible in IE
				}
			});
			autoPopulate.addEvent(oInput, 'blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length) { this.value = this.title; }
			});
		}
	},
	hideLabel:function(sId) {
		var arrLabels = document.getElementsByTagName('label');
		var iLabels = arrLabels.length;
		var oLabel;
		for (var i=0; i<iLabels; i++) {
			oLabel = arrLabels[i];
			if (oLabel.htmlFor == sId) {
				oLabel.className = oLabel.className + ' ' + autoPopulate.sHiddenClass;
			}
		}
	},
	/**
	 * getElementsByClassName function included here for portability.
	 * Remove if you are already using one.
	 * Written by Jonathan Snook, http://www.snook.ca/jonathan
	 * Add-ons by Robert Nyman, http://www.robertnyman.com
	 */
	getElementsByClassName:function(oElm, strTagName, strClassName) {
	    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];      
	        if(oRegExp.test(oElement.className)){
	            arrReturnElements.push(oElement);
	        }   
	    }
	    return (arrReturnElements)
	},
	/**
	 * addEvent function included here for portability.
	 * Remove if you are already using an addEvent/DOMReady function.
	 * Found at http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	 */
	addEvent:function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn](window.event);}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};

/**
 * Init on window load.
 * Replace this with a call to your own addEvent/DOMReady function if you use one.
 */
autoPopulate.addEvent(window, 'load', autoPopulate.init);

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years": 
     var year = expireDate.getYear();     
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;     
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

function AddNote(note,pg){
    var MyCookie = getCookieValue("MyNotes");
	var token = "###"+pg+";"+note+"###";
	if (note != null && note.length>0 && (!MyCookie || MyCookie.indexOf(token) == -1)) {
		writeSessionCookie("MyNotes",((MyCookie) ? MyCookie+token : token));
	}
}

(function($){
	$.fn.extend({
		modalPanel: function(layer,Action) {
			
			//Create our overlay object
			var overlay = $(layer);
			overlay.click(function(){modalHide();});
			//Create our modal window
	//		var modalWindow = $("<div id='modal-window'></div>");
			overlay.css("opacity", 0.5);
			$(document).keydown(handleEscape);	
			$('#closeX').click(function(){modalHide();});	
			$('.closeX').click(function(){modalHide();});	
			switch (Action){
				case 2:
	//				$('#popup').attr('style','height:250px');
	   				$('#CancelExit').click(function(){modalHide();});	
					break;
				case 3:
//				    $('#popup').attr('style',"height:480px");
	   				$('#CancelSend').click(function(){modalHide();});	
	   				$('#ActionSend').click(function(){
						var fname = ($('#fromName').attr('value') == null) ? "" : $('#fromName').attr('value');
						var tname = ($('#toName').attr('value') == null) ? "" : $('#toName').attr('value');
						var temail = ($('#toEmail').attr('value') == null) ? "" : $('#toEmail').attr('value');
						var msg = ($('#message').attr('value') == null) ? "" : $('#message').attr('value');
						var frmcode = ($('#frmCode').attr('value') == null) ? "" : $('#frmCode').attr('value');
						var url = ($('#url').attr('value') == null) ? "" : $('#url').attr('value');
						var pg = ($('#pg').attr('value') == null) ? "" : $('#pg').attr('value');
						$.get(basepath+'scripts/mailer/',{ajax:1, fromName: fname, toName: tname,  toEmail: temail, message: msg, frmCode: frmcode,url: url,pg: pg, SUBMIT: 1}, 
							   function(data){
								var remove = function() { $(this).remove(); };
								$('#frm').html(data);
								if (data.match("Email Sent")){
//									$('#popup').attr('style',"height:220px");
									$('#ActionSend').hide();
									$('#CancelSend').hide();
									}
								else; //$('#popup').attr('style',"height:570px");

							   });	
					});
					break;
				case 4:
//				    $('#popup').attr('style',"height:580px;width: 500px;");
	   				$('#CancelSend').click(function(){modalHide();});	
	   				$('#ActionSend').click(function(){
						var fname = ($("#fromName").attr("value") == null) ? "" : $("#fromName").attr("value");
						var femail = ($("#fromEmail").attr("value") == null) ? "" : $("#fromEmail").attr("value");
						var msg = ($('#message').attr('value') == null) ? "" : $('#message').attr('value');
						var frmcode = ($('#frmCode').attr('value') == null) ? "" : $('#frmCode').attr('value');
						$.get(basepath+'scripts/feedback/',{ajax:1, fromName: fname, fromEmail: femail, message: msg, frmCode: frmcode, btnSubmit: 1}, 
							   function(data){
								var remove = function() { $(this).remove(); };
							//	alert(data);
								$('#frm').html(data);
								if (data.match("Feedback Sent")){
	//								$('#popup').attr('style',"height:220px");
									$('#ActionSend').hide();
									$('#CancelSend').hide();
								}
								else; //$('#popup').attr('style',"height:580px");
							   });	
					});
					break;

				default:
				
			}

		
			//Our function for hiding the modalbox
			function modalHide() {
				$(document).unbind("keydown", handleEscape)
				var remove = function() { $(this).remove(); };
				overlay.fadeOut(remove);
				$('#popup').fadeOut(remove);
			}
			
			//Our function that listens for escape key.
			function handleEscape(e) {
				if (e.keyCode == 27) {
					modalHide();
				}
			}
		}
	});
})(jQuery);

function extractTitle(title){
	var pos = title.indexOf('-');
	if (pos >-1){
		title = title.substring(0,pos-1);
		return title;
	}
	var pos = title.indexOf('&ndash;');
	if (pos >-1){
		title = title.substring(0,pos-1);
	}
	return title;	
}



function setCartPageStatus(){
    if (isInCart()){
		$('li.printbasketadd a').remove();
		$('li.printbasketadd').append('<span>Page added</span>')
	}
}

function displayPopup(data,choice){
	$('#content').append('<div id="popupLayer"></div>');
	$('#content').append(data);
	var layer = $('#popupLayer');
	layer.modalPanel('#popupLayer',choice);
}

$(function() {
		var f= function() { if ($('div#popup') && $('div#popup').attr('class') == 'download' && dldInProgress){
			 $.get(basepath+'scripts/downloads/',{ajax:1,proc:1},function(data){
					$('div#frm').html(data);
					dldInProgress = !data.match("Download complete");
			  });
		} };

    	setInterval( f, 2000 );
});

var dldInProgress = false;
var contentClass = null;
var trigger = null;
var printCartValue = ' ';
var basepath = '/';
$(document).ready(function() {
	var x = document.location.href.replace('http://','');
	var y = $('#logo h1 a').attr('href');
	basepath = x.substring(x.indexOf('/'),x.lastIndexOf('/')+1)+y.replace('index.html','');
	
	$('#print_all').click(function (){
		$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
	});
	 
   $('#delete_all').click(function (){
		$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
	});
   
   $('#email_all').click(function (){
		$('input.'+$(this).attr('class')).attr('checked',$(this).attr('checked'));						     
	});
    
	if (testPersistentCookie() == false) return;	
	$('a.printButton').click(function() {
		window.print();
  });
  
    
    $('li.email a').click(function(){
		var pg = $(this).attr('href');
		var rg = new RegExp("pg\\d+");
		var res = rg.exec(pg);
		$.get(basepath+'scripts/mailer/',{ajax:1, pg:res},function(data){
		displayPopup(data,3);
		});
		return false;		
   });  	

   $('a.external').click(function (){
				var surl = this.href;//.substring(this.href.indexOf('url=')+4);
				$.get(basepath+'scripts/ajdialogs/',{url:surl, dialog:2},function(data){
				displayPopup(data,2);
			});
		return false;
	 });
    $('li.feedback a').click(function(){
   		$.get(basepath+'scripts/feedback/',{ajax:1},function(data){
   		displayPopup(data,4);
   		});
   		return false;		
   });  
   
     $('.downloadButton').click(function (){
   		var dlds = $('input[name=dld]:checked');								
   		var docs = '';
   		for (i=0;i<dlds.length;i++)	docs += ','+dlds[i].value;
   		if (docs.length > 0){
   			docs = docs.substr(1);
   			$.get(basepath+'scripts/downloads/',{ajax:1, dld:docs},function(data){
   				dldInProgress = true;																			 
   				displayPopup(data,5);
   			});
   		}
   		return false;
	 });
   $('.js_rep_header').hide();
   // Cookie js finds if persistent cookies are enabled
	initCart();	
	setCartPageStatus();
});
							
