// JScript source code
// Name: Sanjeev K. Malhotra

var cNamePrefix = 'cTextArea_index';
var cPagePrefix = 'cSavedPage_';
var cExpireDays = 365; //No of days till exipiration of cookies on this site
var emptyNotesMsg = 'You do not have any saved notes';
var emptyPagesMsg = 'You do not have any saved pages';

var pageName = new Array();
pageName[0] = "company_message.html";
pageName[1] = "company_profile.html";
pageName[2] = "company_officers.html";
pageName[3] = "company_facts.html";
pageName[4] = "company_corp_info.html";
pageName[5] = "investment_model.html";
pageName[6] = "investment_scale.html";
pageName[7] = "investment_operations.html";
pageName[8] = "investment_expansion.html";
pageName[9] = "driving_attacking.html";
pageName[10] = "driving_investing.html";
pageName[11] = "driving_growing.html";
pageName[12] = "driving_leveraging.html";
pageName[13] = "gov_message.html";
pageName[14] = "gov_bod.html";
pageName[15] = "gov_principles.html";
pageName[16] = "gov_guidelines.html";
pageName[17] = "gov_charters.html";
pageName[18] = "result_message.html";
pageName[19] = "result_highlights.html";
pageName[20] = "result_report.html";




var pageDesc = new Array();
pageDesc[0] = "Message from the President and Chief Executive Officer";
pageDesc[1] = "Corporate Profile";
pageDesc[2] = "Executive Officers";
pageDesc[3] = "Market Facts";
pageDesc[4] = "Corporate Information";
pageDesc[5] = "Our Investment Story: Multi-layered business model";
pageDesc[6] = "Our Investment Story: Scale";
pageDesc[7] = "Our Investment Story: Franchised operations";
pageDesc[8] = "Our Investment Story: Market presence and expansion";
pageDesc[9] = "Strategic Growth Plan: Attacking Daypart";
pageDesc[10] = "Strategic Growth Plan: Investing";
pageDesc[11] = "Strategic Growth Plan: Growing";
pageDesc[12] = "Strategic Growth Plan: Leveraging";
pageDesc[13] = "Message from the Executive Chairman";
pageDesc[14] = "Board of Directors";
pageDesc[15] = "Principles of Governance";
pageDesc[16] = "Governance Guidelines";
pageDesc[17] = "Charters";
pageDesc[18] = "Message from the Chief Financial Officer";
pageDesc[19] = "Highlights";
pageDesc[20] = "2010 Report Card";



var pageFile = new Array();
pageFile[0] = "company_message.pdf";
pageFile[1] = "company_profile.pdf";
pageFile[2] = "company_officers.pdf";
pageFile[3] = "company_facts.pdf";
pageFile[4] = "company_corp_info.pdf";
pageFile[5] = "investment_model.pdf";
pageFile[6] = "investment_scale.pdf";
pageFile[7] = "investment_operations.pdf";
pageFile[8] = "investment_expansion.pdf";
pageFile[9] = "driving_attacking.pdf";
pageFile[10] = "driving_investing.pdf";
pageFile[11] = "driving_growing.pdf";
pageFile[12] = "driving_leveraging.pdf";
pageFile[13] = "gov_message.pdf";
pageFile[14] = "gov_bod.pdf";
pageFile[15] = "gov_principles.pdf";
pageFile[16] = "gov_guidelines.pdf";
pageFile[17] = "gov_charters.pdf";
pageFile[18] = "result_message.pdf";
pageFile[19] = "result_highlights.pdf";
pageFile[20] = "result_report.pdf";




//-- This function exetends the array indexOf property which is no longer supported in IE8. That is why this funtion is required
Array.prototype.indexOf = function (obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] == obj) { return i; } } return -1; }

//Get length of an associative array while causing the fewest bugs as recommended on StackOverflow.com
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get Cookie Value by key value passed by c_name
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

//--Jan 14, 2010; Delete this function, may not be needed
// this deletes the cookie when called
// to delete the cookie,  pass the "name" of the cookie, and simply pass '/' for the path and '' for the domain
/*function Delete_Cookie(name, path, domain) {
    
    if (Get_Cookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}*/

function removeElement(parentDiv, childDiv) {
    
    if (childDiv == parentDiv) {
        alert("The parent div cannot be removed.");
    }
    else if (document.getElementById(childDiv)) {
    //alert("ParentDiv Value:" + parentDiv + "  " + "ChildDiv:" + childDiv);
        var child = document.getElementById(childDiv);
        var parent = document.getElementById(parentDiv);
        parent.removeChild(child);
    }
    else {
        alert("Child div has already been removed or does not exist.");
        return false;
    }
    check_pnelements();
}


// Set a cookie by key value (c_name), value, and number of days it will expire (expirerdays)
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}


//Create a cookie with the prefix cTextArea_index for the key value and append the timestamp to the prefix
//Then Set the value of the cookie to the cookie value
function writeNoteToCookie() {
    var d = new Date();

    // !Look up and return index of html file in the PageName array and append it to prefix cTextArea_index_
    
    var fileName = getUrlFileName();
    var pageId = pageName.indexOf(fileName);
         
    var cs = 'cTextArea_index_' + pageId.toString() + '_' + d.getTime();
    setCookie(cs, document.getElementById('txtNote').value, cExpireDays);
    document.getElementById("savedNoteAlert").style.display = 'block';
}

function checkCookieNote() {

    var fileName = getUrlFileName();
    var pageId = pageName.indexOf(fileName);
    var lastCookieNote = "";
    var myfilteredList = jaaulde.utils.cookies.filter(/^cTextArea/);
    var myfilteredPageList = jaaulde.utils.cookies.filter(/^cSavedPage/);
    var fnameSplit;
    var pnameSplit;
    var pSaved = false;

    for (var fname in myfilteredList) {
       
        fnameSplit = fname.split("_");
        if (pageId == fnameSplit[2]) {
            lastCookieNote = myfilteredList[fname];
        }

    }
    document.getElementById('txtNote').value = lastCookieNote;

    for (var pname in myfilteredPageList) {
        pnameSplit = pname.split("_");
        if (pageId==pnameSplit[1]) {
	        pSaved = true;
    	    break;
        } 
      }
    if (pSaved){
        document.getElementById('ipSavePageStatus').src = "images/but_page_saved.jpg";
    }else{
        document.getElementById('ipSavePageStatus').src = "images/save_page.jpg";
    }
}

//Create a cookie with the prefix stored in '' for the key value and append the page to the prefix
//Then Set the value of the cookie to the cookie value
function writePageToCookie() {
    var d = new Date();
    var cp;
    // !Look up and return index of html file in the PageName array and append it to prefix cTextArea_index_

    var fileName = getUrlFileName();
    var pageId = pageName.indexOf(fileName);

    cp = cPagePrefix + pageId.toString();
    setCookie(cp, "saved", cExpireDays);
    document.getElementById('ipSavePageStatus').src = "images/but_page_saved.jpg";
}


// Get list of all the cookies in a site
var getCookies = function () {
    var pairs = document.cookie.split(";");
    var cookies = {};
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split("=");
        cookies[pair[0]] = unescape(pair[1]);
    } return cookies;
}


//--Jan 14, 2010; Delete this function, may not be needed
//This function is for testing and pulling a list of cookies and their values
//Filter the list of cookies according to the prefix "cTextArea"
var showCookies = function () {
    var myCookies = getCookies();
    var myfilteredList = jaaulde.utils.cookies.filter(/^cTextArea/);

    for (var name in myCookies) {
        document.write("Cookie List =>" + name + " : " + myCookies[name] + "<br/>");
    }

    for (var fname in myfilteredList) {
        document.write("Filtered List =>" + fname + " : " + myfilteredList[fname] + "<br/>");
    }

}


//Dynamically generate and display a series of collapsible panels. One for each each cookie on the site storing the User's notes
function displayNotes() {
    var s = "";
    var i = 0;
    var myfilteredList = jaaulde.utils.cookies.filter(/^cTextArea/); //Retrieve all cookies where the key name starts with "cTextArea"
    var fnameSplit;
    var pageId;
    var Timestamp;
    var dDate;

    for (var fname in myfilteredList) {

        i++;       
        fnameSplit= fname.split("_");
        pageId = fnameSplit[2];
        Timestamp = fnameSplit[3];
        
        trackingNo = pageId + '_' + Timestamp;
        var d = EpochToHuman(Timestamp);        
        var fslashstr = '\/';
        var estring = '\'\'';
        var itemId = 'item' +i;
        
        
        s = s + '<div class=\"dragbox\" id=\"' + itemId + '\" >';
        s = s + '<h2>';
       
        
        //---Working script
        //--setCookie(fname, "", -1) deletes the cookie by value fname
        s = s + '<input type=\"button\" class=\"delete_input\" name=\"handler\" value="" id=\"delete_' + i + '\" onClick="removeElement(\'lblSavedNotes\',\'' + itemId + '\'); setCookie(\'' + fname + '\','+ estring + ',-1); \"/>';
        s = s + '</h2>';
        s = s + '<div  align=\"left\" class=\"dragbox-content\" id=\"note' + trackingNo + '\">';
        s = s + myfilteredList[fname];
        s = s + '<div class=\"bottom\">';
        s = s + '<p  align=\"left\" class=\"link\"><a href=\"' + pageName[pageId] + '\"> View ' + pageDesc[pageId] + ' page</a></p>';

        s = s + '<p  align=\"left\" class=\"last_saved\"> Last saved on ' + d.toLocaleString() + '</p>'; ;
        s = s + '<p  align=\"left\"><input name=\"items\" type="checkbox" value=\"' + trackingNo + '\" /></p>';
        s = s + '</div>';
        s = s + '</div>';
        s = s + '</div>';
    }
    if (i > 0) {
        (document.getElementById('lblSavedNotes').innerHTML = s);
        document.getElementById('btnPrintNotes').style.visibility = 'visible';  
		document.getElementById('btnDownloadnotes').style.visibility = 'hidden';
     
    } else {
        document.getElementById('lblSavedNotes').innerHTML = emptyNotesMsg;
        document.getElementById('btnPrintNotes').style.visibility = 'hidden';
		document.getElementById('btnDownloadnotes').style.visibility = 'hidden';
	}
}


function EpochToHuman(tstamp) {

    var inputtext = (tstamp*1);
    var outputtext = "";
    var extraInfo = 0;
            
    if (inputtext > 1000000000000) {
        outputtext += "<b>Assuming that this timestamp is in milliseconds:</b><br/>";
    } else {
        if (inputtext > 10000000000) extraInfo = 1;
        inputtext = (inputtext * 1000);
    }
    var datum = new Date(inputtext);
    return datum
}

function displayPages() { 
    var s = "";
    var i = 0;
    filterWord='/^'+cPagePrefix+'/'

    var myfilteredList = jaaulde.utils.cookies.filter(/^cSavedPage/); //Retrieve all cookies where the key name starts with "cTextArea"
     var fnameSplit;
     var pageId;
     var pItemId;
     var estring = '\'\'';

    for (var fname in myfilteredList) {

        i++;                
            fnameSplit= fname.split("_");
            pageId = fnameSplit[1];
            pItemId = 'pItem' + i;
            s = s + '<div class=\"dragbox\" id=\"' + pItemId +'\">';

            s = s + '<h2>';
            //--setCookie(fname, "", -1) to delete the cookie
            s = s + '<input type=\"button\" class=\"delete_input\" name=\"handler\" value=\"\" id=\"deleteSavedPage_' + i + '\" onClick="removeElement(\'lblSavedPages\',\'' + pItemId + '\'); setCookie(\'' + fname + '\',' + estring + ',-1); \"/>';

            s = s + '</h2>';        
            s = s + '<div class=\"dragbox-content\" id=\"savedPage_' + pageId + '\">'
	        s = s + '<div class=\"bottom\">';

    	    s = s + '<p align=\"left\">' +pageDesc[pageId] + '</p>';
        	s = s + '<p  align=\"left\" class=\"link\"><a href=\"' + pageName[pageId] + '\"> View ' + pageDesc[pageId] + ' page</a></p>';

        s = s + '<p  align=\"left\"><input name=\"pitems' + i + '\" type="checkbox" value=\"' + pageFile[pageId] + '\" /></p>';
        s = s + '</div>';

        s = s + '</div>';
        s = s + '</div>';
        }


        if (i>0){
            (document.getElementById('lblSavedPages').innerHTML = s);
            document.getElementById('btnPrintPages').style.visibility = 'visible'; 
            
        }else{

        document.getElementById('lblSavedPages').innerHTML = emptyPagesMsg;
            document.getElementById('btnPrintPages').style.visibility = 'hidden';
        }
}


function getUrlFileName(){
   
    var url = window.location.href;
    var lastSlash = url.lastIndexOf("/");
    var firstQuestionMark = url.indexOf("?");
 
    if (firstQuestionMark == -1) {
        firstQuestionMark = url.length;
    }

    var fileName = url.substring(lastSlash + 1, firstQuestionMark);
    return fileName;
}


function validate(form) { 

    var total=""
	if (typeof document.action_notes.items.length === 'undefined') {
   /*then there is just one checkbox with the name 'items', no array*/
        if (document.action_notes.items.checked == true )
            total += document.action_notes.items.value + "\n"
	}
	
    for (var i = 0; i < document.action_notes.items.length; i++) {
        if (document.action_notes.items[i].checked)
            total += document.action_notes.items[i].value + "\n"
    }
    if (total == "") {
        alert("Select  1 or more notes");
        return false;
    } else {
        //alert(total);
    }
}

function MyGetUrlParams(){
    var url_params = new Array();
    var urla = location.href.substring(location.href.indexOf('?') + 1).split('&');
    var key;
    var pos;
    var value;
   	for(i=0;i< urla.length ;i++){
       pos = urla[i].indexOf('=');
       
       key = urla[i].substring(0, pos)+i;
       value = urla[i].substring(pos + 1);
       url_params[key] = value;
    }
   	for(var k in url_params)
   	{

	   if (k.indexOf('indexOf') > -1){
		   delete url_params[k] //Delete any element from the associative array where the key value contains 'indexOf'
	  }
	}
    return url_params;
 }


 function displayPrintNotes() {
    var pns = new String();
    
    var timestamp;
    var params = MyGetUrlParams();
    var fnameSplit;
    var pageId;
    var timestamp;
    var trackingNo;

    var cookieName;
	var d;
	var txt='';
	
    for (var key in params) {
			if (key.indexOf('indexOf') >-1){
				delete params[key];	
			}else{
				txt = txt + 'key: ' + key +'</br>';

    	    	trackingNo = params[key];		
				try{
					pageId = trackingNo.split("_")[0];
	    		    timestamp = trackingNo.split("_")[1];
					d = EpochToHuman(timestamp);
			        cookieName = cNamePrefix + '_' + params[key];
    			    pns = pns  + '<p>' + getCookie(cookieName) + '</p>'
					pns = pns +'<p>Saved to the <strong><a href=\"'+ pageName[pageId]  +'\">'+ pageDesc[pageId] +'</a></strong> page on '+ d.toLocaleString() +'<p>';
	        		pns = pns + '<hr class=\"print donotprint\" />';
				}
				catch(err)
				{
					alert("Catching error:" + err.description);	
				}
			}
    	}
			document.getElementById('lblprint_notes').innerHTML=pns;
 }


 function WriteToFile(field) {
     var fso = new ActiveXObject("Scripting.FileSystemObject");
     var s = fso.CreateTextFile("C:\\notes.rtf", true);

     var timestamp;
     var cbvalue;
     var fnameSplit;
     var pageId;
     var timestamp;
     var trackingNo;

     var cookieName;
	 var newURL;
		  s.WriteLine('To print your saved pages Press Ctrl and the \'P\' key on your keyboard, or select File, then Print from the menu.');
          s.WriteLine('Notes on the Tim Horton\'s plc Annual Report 2009');
		  s.WriteLine('');
  		  s.WriteLine('');
          
     for (var i = 0; i < field.length; i++) {
         if (field[i].checked) 
         {
			 newURL = "";
             cbvalue = field[i].value;
             trackingNo = cbvalue;
             pageId = trackingNo.split("_")[0];
             timestamp = trackingNo.split("_")[1];
			 var d = EpochToHuman(timestamp);
       
             cookieName = cNamePrefix + '_' + cbvalue;
			 s.WriteLine('');
             s.WriteLine(getCookie(cookieName));
			 s.writeLine('Saved to the ' + pageDesc[pageId] + ' page on ' + d.toLocaleString());
             s.writeLine(pageName[pageId]);
			var pcol=window.location.protocol ;
			var ht = window.location.host;
			var pname=pageName[pageId];
			newURL = pcol + "//" + ht + "//" + pname;
			s.writeLine(newURL);
 
			s.WriteLine('***********************');
         }
     }
     s.close();
 }

 function check_pnelements() {

       var ps;
       var ns;
       ps = document.getElementById('lblSavedPages').innerHTML;
       if (ps == "" || ps == emptyPagesMsg) {
           document.getElementById('btnPrintPages').style.visibility = 'hidden';
           document.getElementById('lblSavedPages').innerHTML = emptyPagesMsg; 
       } else {
         document.getElementById('btnPrintPages').style.visibility = 'visible';
     }

     ns = document.getElementById('lblSavedNotes').innerHTML;
     
     if (ns == "" || ns == emptyNotesMsg) {
         document.getElementById('btnPrintNotes').style.visibility = 'hidden';
         document.getElementById('btnDownloadnotes').style.visibility = 'hidden';
         document.getElementById('lblSavedNotes').innerHTML = emptyNotesMsg;
     } else {
         document.getElementById('btnPrintNotes').style.visibility = 'visible';
         document.getElementById('btnDownloadnotes').style.visibility = 'visible';
     }
 }
 
