/* Hides form label, shows input value in search field
Source: http://www.456bereastreet.com/lab/autopopulating-text-input-fields/ */

/**
 * 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);


//
// trigger onLoad function (do_onload)
//
if (window.addEventListener)
{
	window.addEventListener("load", do_onload, false);
}
else
{
	if (window.attachEvent)
	{
		window.attachEvent("onload", do_onload);
	}
	else
	{
	if (document.getElementById)
		{
			window.onload = do_onload;
		}
	}
}


function do_onload()
{
	setJSFunctionality();
}

function setJSFunctionality ()
{
	if(document.getElementById("jsPrintPage"))
	{
		document.getElementById("jsPrintPage").style.display = "block";
	}


	
if (!document.getElementsByTagName) return false;
	var rows = document.getElementsByTagName("tr");
	for (var i=0; i<rows.length; i++) {
		if(rows[i].parentNode.nodeName=='TBODY') {
			rows[i].onmouseover = function() {
				$(this).addClass("rowhighlight"); 
			}
			rows[i].onmouseout = function() {
				$(this).removeClass("rowhighlight");
			}
		}
	}


	var links = document.getElementsByTagName("a");
	for (var i=0; i < links.length; i++) {
	    if (links[i].className.match("popup")) {
			links[i].onclick = function() {
		        window.open(this.href);
		        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 establishPgId()
{
	var contentClass = $('body').attr("class");
	var rg = new RegExp("pg\\d+");
	var res = rg.exec(contentClass);
	contentClass = res;
	return res;
}	
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;
}
	
function cookieValue()
{
	if (getCookieValue('PrintCart') == false)
	{
	} 
	else 
	{
		printCartValue = getCookieValue('PrintCart');				
		return printCartValue;
	}
}	
function updateCookie(printCartValue)
{
	var myCookieName = 'PrintCart';
	var myCookiePeriod = 'months';
	var myCookieOffset = '1';
	writePersistentCookie (myCookieName, printCartValue, myCookiePeriod, myCookieOffset);
}	

function isInCart(){
		var value =  BasketCookie;
		return (value != null && value.indexOf(establishPgId())>-1)
}

function initCart()
{
	contentClass = establishPgId();
	cookieValue();	
}	
function AddNote(note,pg){
	NotesCookie = $.ajax({type: 'POST',url: basepath+'scripts/notepad/',async: false,data: {ajax: 1, ajxcmd: 'addnote',add:pg, note: note},dataType: 'text'}).responseText;
	setNotepadPageStatus();
}

function isInNotepad(){
	var pg = $('body').attr('class');
	var rg = new RegExp("pg\\d+");
	var res = rg.exec(pg);
	pg=res;
	var MyCookie = NotesCookie;
	return (MyCookie && MyCookie.indexOf('###'+pg) > -1);
}

function setNotepadPageStatus(){
    if (isInNotepad()){
		$('li.notes > #notes').text('Edit');
	//	$('li.note > span.slashsep').remove();
	}
}
(function($){
	$.fn.extend({
		modalPanel: function(layer,Action) {
			var width =  $('html').width();
			var height = $('html').height();
			//Create our overlay object
			var overlay = $(layer);
			overlay.width(width+"px");
			overlay.height(height+"px");
			overlay.css("position","absolute");
			overlay.click(function(){modalHide();});
			$('#popup').draggable();
			//Create our modal window
	//		var modalWindow = $("<div id='modal-window'></div>");
			overlay.css("opacity", 0.5);
			$(document).keydown(handleEscape);	
			$('#closeX').click(function(){modalHide();});	
			$('.close').click(function(){modalHide();});	
			switch (Action){
				case 1:
		//			$('#popup').attr('style','height:250px');
	   				$('#CancelNote').click(function(){modalHide();});	
	   				$('#SaveNote').click(function(){
								var pg = $('body').attr('class');
								var rg = new RegExp("pg\\d+");
								var res = rg.exec(pg);
								AddNote($('#note_ta').attr('value'),res);
								setNotepadPageStatus();
								modalHide();
							});				   
					break;
				case 2:
	//				$('#popup').attr('style','height:250px');
	   				$('#CancelExit').click(function(){modalHide();});	
	   				$('#DoExit').click(function(){document.location.href=$('#goto').attr('href')});	
					break;
				case 3:
	   				$('#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 oimp = ($("input[name='overall_impression']:checked").val() == null) ? "" : $("input[name='overall_impression']:checked").val();
						var or = ($("input[name='online_review']:checked").val() == null) ? "" : $("input[name='online_review']:checked").val();
						var rpv = ($("input[name='read_printed_version']:checked").val() == null) ? "" : $("input[name='read_printed_version']:checked").val();
						var uii = ($("input[name='useful_inverstor_info']:checked").val() == null) ? "" : $("input[name='useful_inverstor_info']:checked").val();
						var msg = ($('#comments').attr('value') == null) ? "" : $('#comments').attr('value');
						var frmcode = ($('#frmCode').attr('value') == null) ? "" : $('#frmCode').attr('value');
						$.get(basepath+'scripts/feedback/',{ajax:1, overall_impression: oimp, online_review: or,  read_printed_version: rpv, useful_inverstor_info: uii, comments: 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();
								}
								else; //$('#popup').attr('style',"height:580px");
							   });	
					});
					break;
					case 5:

					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.basket > #printbasket').remove();
		$('li.basket > span').remove();
	}
}
function setLinkCartStatus(){
    if (isInLinkCart()){
		$('li.linkBasketAdd > #linkbasket').remove();
		$('li.linkBasketAdd > span.slashsep').remove();	}
}
function displayPopup(data,choice){
	$('body').append('<div id="popupLayer"></div>');
	$('body').append(data);
	var layer = $('#popupLayer');
	layer.modalPanel('#popupLayer',choice);
	
}


function refreshDownload(){
		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");
			  });
		}
}
	
$(function() {
    	setInterval( "refreshDownload()", 2000 );
});

var dldInProgress = false;
var contentClass = null;
var trigger = null;
var printCartValue = ' ';
var basepath = '/';
var NotesCookie;
var BasketCookie;

$(document).ready(function() {
	//for table row
	var x = document.location.href.replace('http://','');
	var y = $('#header_title a').attr('href');
	basepath = x.substring(x.indexOf('/'),x.lastIndexOf('/')+1)+y.replace('index.html','');
	 $('#print_all').click(function (){
	 	var mstatus = ($(this).attr('checked')) ? true : false;
		$('input[@class = "'+$(this).attr('class')+'"]').attr('checked',mstatus);						     
	});
   $('#delete_all').click(function (){
		 	var mstatus = ($(this).attr('checked')) ? true : false;
			$('input[@class = "'+$(this).attr('class')+'"]').attr('checked',mstatus);							     
	});
   $('#email_all').click(function (){
		 	var mstatus = ($(this).attr('checked')) ? true : false;
			$('input[@class = "'+$(this).attr('class')+'"]').attr('checked',mstatus);			
	});
    
//	if (testPersistentCookie() == false) return;	
	$('a.printButton').click(function() {
		window.print();
  });
  NotesCookie = $.ajax({type: 'GET',url: basepath+'scripts/notepad/',async: false,data: {ajax: 1, ajxcmd: 'getcookie'},dataType: 'text'}).responseText;
  BasketCookie = $.ajax({type: 'GET',url: basepath+'scripts/print/',async: false,data: {ajax: 1, ajxcmd: 'getcookie'},dataType: 'text'}).responseText;
  
  
  $('#notes').click(function(){
				 var pg = $(this).attr('href');
				 var rg = new RegExp("pg\\d+");
		 		 var res = rg.exec(pg);
				 $.get(basepath+'scripts/notepad/',{ajax:1,ajxcmd: 'popup',add: res},function(data){
					displayPopup(data,1);
				 });
				 return false;
   });  					   
   
   
    $('li.emailTool 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;		
   });  	

  $('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;
	 });
   // Cookie js finds if persistent cookies are enabled
//	initCart();	
	setCartPageStatus();
	setNotepadPageStatus();
	
	$("table tbody tr").mouseover(function(){
      $(this).addClass("rowhover");
    }).mouseout(function(){
      $(this).removeClass("rowhover");
    });
    
});
