
/*==============================================================================

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;     
}


/*Cart functions*/
function removeFromCart(previewTag)
{
	var tempArray = printCartValue.split(',')
	var newArray = ' ';			
	for (i=0;i<tempArray.length;i++)
	{
		if ( tempArray[i] == contentClass)
		{
		}
		else
		{
			if (newArray == ' ')
			{
				newArray = tempArray[i];
			}
			else
			{
				newArray += ','+tempArray[i];	
			}
		}
	}
	printCartValue = newArray;
	updateCookie(printCartValue);
	reloadCart();
	loadPreview(); 
}	

function addToCart()
{
	if (printCartValue == ' ')
	{
		printCartValue = contentClass;				
	} 
	else
	{
		printCartValue += ','+contentClass;		
	}
	updateCookie(printCartValue);
}	
function establishPgId()
{
	var contentClass = $('body').attr("class");
	var rg = new RegExp("pg\\d+");
	var res = rg.exec(contentClass);
	contentClass = res;
	return res;
}		
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 initCart()
{
	contentClass = establishPgId();
	cookieValue();	
}	
function isInCart(){
		var value =  cookieValue();
		return (value != null && value.indexOf(establishPgId())>-1)
	}
	function isInLinkCart(){
		var value =  getCookieValue('LinkCart');
		return (value != false && value.indexOf(establishPgId())>-1);
	}
/*
Core site functionalities related functions
*/
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;
}
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.note > #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();});
			//Create our modal window
	//		var modalWindow = $("<div id='modal-window'></div>");
			overlay.css("opacity", 0.5);
			$(document).keydown(handleEscape);	
			$('#closeX').click(function(){modalHide();});	
			switch (Action){
				case 1:
	   				$('#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();});	
					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){
							//	   alert(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();
									$('#CancelSend').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.printbasketadd').remove();
}
function setLinkCartStatus(){
    if (isInLinkCart()) 		$('li.linkbasketadd').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 = '/';
$(document).ready(function() {
	var x = document.location.href.replace('http://','');
	var y = $('#siteLogo > 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();
  });
  NotesCookie = "";//$.ajax({type: 'GET',url: basepath+'scripts/notepad/',async: false,data: {ajax: 1, ajxcmd: 'getcookie'},dataType: 'text'}).responseText;
  //  alert(NotesCookie);
  
  $('#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.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;		
   });  	

  $('li > a.feedback').click(function(){
		$.get(basepath+'scripts/feedback/',{ajax:1},function(data){
		displayPopup(data,4);
		});
		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;
	 });
   
   $('.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();
	setLinkCartStatus();
	
	//if (!document.getElementsByTagName) return false;
	
	//var rows = $("table > tbody > tr");
	//for (var i=0; i<rows.length; i++) { 
	//	if(rows[i].parentNode.nodeName == 'tbody') {
	//		rows[i].onmouseover = function() {
	//			$(this).addClass("rowhover"); 
	//		}
	//		rows[i].onmouseout = function() {
	//			$(this).removeClass("rowhover");
	//		}
	//	}
	//}
    $("table tbody tr").mouseover(function(){
      $(this).addClass("rowhover");
    }).mouseout(function(){
      $(this).removeClass("rowhover");
    });

	
});



