/*
 * The following JavaScript is an adaptation of the original, by Shawn (?), to be used with std. HTML as well as 
 * 	any other source of disclaimer-based content (for example, embedded links in XML fed to a Flash movie/swf.
 * 
 * 	To enable the pop-up disclaimer functionality the following conditions must be met:
 * 	+ Add (within a script element) to any HTML-rendered content: addDisclaimer("disciPod","discGlobalEpa","[etc...]");
 * 	+ Create a link using the following format:
 * 		<a href="javascript:showDisclaimer('disciPod')" title="iPod">*</a> (necessary for Flash XML, etc)
 * 		<a href="javascript:showDisclaimer('EPA')" title="EPA">&dagger;</a> (necessary for Flash XML, etc)
 * 													- OR / [AND] -
 * 		<a href="#iPod" onclick="showDisclaimer('disciPod')" title="iPod">[&Dagger;]</a> (preferred for HTML content)
 * 		<a href="#discGlobalEpa" onclick="showDisclaimer('EPA')" title="EPA">[**]</a> (preferred for HTML content)
 * 
 * 	To view all the disclaimers in the pop-up, call showDisclaimer() with an empty [/any] string, as in the following link:
 * 		<a href="#VIEW_ALL" onclick="showDisclaimer('')" title="View All Disclaimers">View All Disclaimers</a> (preferred for HTML content)
 * 
 * 	The order in which disclaimers are added, using the addDisclaimer method, is the order they appear in the pop-up.
 * 	The symbol representing the disclaimer is determined by the order it is added (not the character used in the link).
 * 	The symbol order is provided below in the array variable, arrDisclaimerLegend.
 * 
 *  6.1.10
 *  Adding piggy-back code to remove the need for the addDisclaimer function. The first section of code below scans the DOM for links
 *  with 'showDisclaimer' in the href attribute and tries to load disclaimer keys accordingly. An event to handle the popup is also used,
 *  so we can use this code in step 4 of Build and Price (e.g.), and not have problems. This eliminates the need to keep track of 
 *  tokens and simplifies maintenance of disclaimer links. On that note, why use multiple token types at all if we have popups? Tracking 
 *  tokens adds much complexity to this system because the order in which we load keys determines the token used in the link text.
 *  
 *  Flash files still use the flash disclaimer code at the bottom of this file but those functions should be deprecated and converted.
 *  Flash-specific functions require disclaimer text to be kept in XML files which means more maintenance.
 */

// Global Pop-Up HTML Variables
var pageTitle = "", pageHeight = 280;
var arrDisclaimerKeys = new Array(), arrDisclaimerData = new Array(), arrLoadedDisclaimerKeys = new Array();
var arrDisclaimerLegend = ["*","&dagger;","&Dagger;","**","&dagger;&dagger;","&Dagger;&Dagger;","***","&dagger;&dagger;&dagger;","&Dagger;&Dagger;&Dagger;"];
var disclaimerPop = $("<div><div class=\"popDiv popCenter\"><ul><div id=0/><div id=1/><div id=2/><div id=3/><div id=4/><div id=5/><div id=6/><div id=7/><div id=8/><div id=9/></ul></div></div>");



function stripKey ( dataStr ) {
	return $.trim(dataStr.replace(/[\)\('"]+/g, ""));
}


function extractKeys (linkObj) {
	var mask = $(linkObj).attr('href').match(/showDisclaimer\([a-z0-9_,'"\s]+\)/i);
	if (mask != null) {
		var matchDisclaimer = (String(mask[0].match(/\([a-z0-9_,'"\s]+\)/i)[0]).split(","));
		if (matchDisclaimer.length) {
			return $.map(matchDisclaimer, stripKey );	        
		} else return new Array (null);
	} else {
		return new Array (null);
	}
}

function verifyKey (dbKey) {	
    return $.inArray(dbKey, arrDisclaimerKeys);    
}

function getSortPriority (dbKey) {
    var sortPriority = -1;
    if (dbKey.search(/airbag/i) > -1) {
        sortPriority = 0;
    } else if (dbKey.search(/msrp/i) > -1) {
        sortPriority = 1;
    }
    return sortPriority;
}

function disclaimerClick () {
    // extract key
    // if key is loaded, display the disclaimer
	var extract = extractKeys(this);
	var title = (extract[1].length) ? extract[1] : $(this).attr('title');
	var dbKey = extract[0];
	
	if (dbKey.length == 0) {
        // show all link
		showDisclaimer ("", title);
	} else {
	
		try {
		    if (verifyKey(dbKey) == -1) {
		        // we enter here if a key is being requested that has not yet been loaded.
			    // either from flash object or build and price
		    	// or from 'show all' links
		    	
		    	// build and price semi-hack
		    	// can't really name the MSRP disclaimer by name, can't really start from scratch either
		    	// can't have duplicate MSRP disclaimers
		    	// so we just unload by doing a regex match on the array items
		    	if ($(this).hasClass('bprMSRPswap')) {
		    			// need to parse out old MSRP
		    			var splicePoint = 0;
			    		$.each(arrDisclaimerKeys, function (idx, item) {
			    			
			    			if (item.search(/suggestedprice/i) > -1) {
			    				splicePoint = idx;
			    			}
			    		});
			    		//alert ('insertPoint: ' + splicePoint + '\n' + dbKey);
			    		arrDisclaimerKeys.splice (splicePoint, 1, dbKey);
			    		loadDisclaimers(arrDisclaimerKeys, dbKey, title);
		    		
		    	} else {
		    		arrDisclaimerKeys.push (dbKey);
			        loadDisclaimers([dbKey], dbKey, title);	    		
		    	}
			} else {
			    showDisclaimer(dbKey, title);
			}
		} catch (e) {
			alert (e + "\nhref: " + $(this).attr('href') + "\nkey: " + dbKey + "\narray length: " + arrDisclaimerKeys.length);
		}
	
	}
	
	// suppress regular functionality
	return false;
}

function disclaimerSweep () {
	// this looks a lot like what goes on during page load
	var returnArray = new Array ();
	
	if ($('a[href*=showDisclaimer]') != null) {
		$('a[href*=showDisclaimer]').each ( function () {
		    // attempt to load the db key
		    try {
		    	var extract = extractKeys(this);
		    	dbKey = extract[0];
		        if ((verifyKey(dbKey) == -1) && (dbKey != '')) {	        	
		        	phase = '1B';
		        	if (dbKey != null) { // ignore the "show all" links
		        		returnArray.push (dbKey);
		        		phase = '2A';
			            var sPriority = getSortPriority(dbKey);
			            if ((sPriority >= 0) && (arrDisclaimerKeys.length > 0)) {
			            	// for (j=arrDisclaimerKeys.length;j==0;j--) {	            	
			            	//     if (sPriority > getSortPriority(arrDisclaimerKeys[j]) {
			            	//         splice, break;
		            	 	if (getSortPriority(arrDisclaimerKeys[0]) == 0) {
			            		arrDisclaimerKeys.splice (sPriority, 0, dbKey);
			            	} else {
			            		arrDisclaimerKeys.unshift (dbKey);		            		
			            	}	            	
			            		
			            } else {
			            	phase = '3B';
			            	arrDisclaimerKeys.push(dbKey);
			            	/*
			            	if (arrDisclaimerKeys.length) {
			            	    if (getSortPriority(arrDisclaimerKeys[0]) >= 0){
			            		    arrDisclaimerKeys.push (dbKey);
			            	    } else {
			            	    	alert ('unshift');
			                        arrDisclaimerKeys.unshift (dbKey);
			            	    }
			            	} else {
			            		alert ('no array');
			            		arrDisclaimerKeys.push(dbKey);
			            	}
			            	*/
			            }		            
		        	}
				}
		    } catch (e) {
		    	 alert (e + "\nhref: " + $(this).attr('href') + "\nkey: " + dbKey + "\nphase: " + phase + "\narray length: " + arrDisclaimerKeys.length); 
		    }
		    
		}).click (disclaimerClick);
	}
	return returnArray;
	
}

function reloadDisclaimers () {
	var loadedKeys = new Array ();
	loadedKeys = disclaimerSweep ();
	if (loadedKeys.length > 0) {
		// remove dupe MSRP disclaimers
		// this is problematic
		loadedKeys = $.map(loadedKeys, function (item) {	
			
			if (item.search(/suggestedprice/i) > -1) {
				return null;
			} else {
				return item;
			}
		});
		
		loadDisclaimers(loadedKeys);
		
		// could functionize this part but it's small already
		var base = arrDisclaimerKeys.length - 2;
		$.each (loadedKeys, function (idx, newKey) {		
			$('a[href*=' + newKey + ']').html(arrDisclaimerLegend[idx + base]);
			arrDisclaimerKeys.push (newKey);
		})
	}
}

$(document).ready ( function () {
	arrDisclaimerKeys = new Array();
	var dbKey = "";
	var phase = 0;
	
	arrDisclaimerKeys = disclaimerSweep();	
	
	// load the disclaimers
	loadDisclaimers(arrDisclaimerKeys);
	// token swaps
	$.each (arrDisclaimerKeys, function (idx, d) {
		$('a[href*=' + d + ']').html(arrDisclaimerLegend[idx]);
	});
	
});


function loadDisclaimers(a, disclaimerKey, disclaimerTitle){
	// added the ability to define a showDisclaimer callback for inline disclaimer loads
	for (var i=0; i < a.length; i++)
	{
		if(!(a[i] in arrayConverter(arrLoadedDisclaimerKeys) )) {
			arrLoadedDisclaimerKeys.addItems ( a[i] );
			var strHtml = disclaimerPop.html();
			$.get("/MMNA/legalDisclaimerAction.do?disclaimerKey="+ a[i], 
				function(data) {
				    var newData = $.trim(data.replace(/^\x28/, ""));
				    if (newData.charAt(newData.length-1) == ")") {
				    	newData = newData.substring(0, newData.length-1);
				    }
				    
				    var dataObj = $.parseJSON(newData);
	    			arrDisclaimerData.addItems({
	    				key: dataObj.disclaimerKey,
	    				data: dataObj.body
	    			});
	    			
	    			if ((dataObj.disclaimerKey == disclaimerKey) && (disclaimerKey != undefined)) {	    				
	    				showDisclaimer(disclaimerKey, disclaimerTitle);
	    			};
	     		}
			, "text");
			 
		}
	}
}

/* marking this for deprecation */
function addDisclaimer()
{ 	
 	// This method may have one/many argument/s (the key, ie. addDisclaimer("disciPod"))
	// and it may be called more than once on pageload via JSP, HTML, properties, etc.
	for (var a=0; a < arguments.length; a++) arrDisclaimerKeys.addItems(arguments[a]);
	if (arrDisclaimerKeys.length > 0) arrDisclaimerKeys = arrDisclaimerKeys.getUnique();
 
	loadDisclaimers(arrDisclaimerKeys);
}

function clearDisclaimer()
{ 	
	arrDisclaimerKeys = new Array(), arrDisclaimerData = new Array(), arrLoadedDisclaimerKeys = new Array();
	disclaimerPop = $("<div><div class=\"popDiv popCenter\"><ul><div id=0/><div id=1/><div id=2/><div id=3/><div id=4/><div id=5/><div id=6/><div id=7/><div id=8/><div id=9/></ul></div></div>");
}


function getDisclaimerData(discKey){
	
	for (var i=0; i < arrDisclaimerData.length; i++)
	{
		if( arrDisclaimerData[i].key ==  discKey ) {
			return arrDisclaimerData[i].data;
		}
	}
	
	return '';
}

function showDisclaimer(objName) 
{	
	// Pass in title via showDisclaimer("disciPod","iPod")
	if (disclaimerPop.find("li").html() == null)
	{
		for (var i=0; i < arrLoadedDisclaimerKeys.length; i++)
		{
			var strDisclaimerKey = arrLoadedDisclaimerKeys[i];
			var strDisclaimerData = getDisclaimerData ( strDisclaimerKey );			
			disclaimerPop.find("div#"+i).append($("<li />").append($("<sup />").append(
				$("<span />").html(arrDisclaimerLegend[i]).addClass("discListSymb"))
				).append(strDisclaimerData).addClass(strDisclaimerKey)
			);
			if (pageHeight < 500)
			{
				var charsPerLine = 100;
				var incrHeight = baseHeight = 35;
				var intDataChars = strDisclaimerData.length;
				incrHeight *= parseInt(intDataChars / charsPerLine);
				if (intDataChars % charsPerLine != 0) incrHeight += baseHeight;
				pageHeight += incrHeight;
			}
		}
	}
	
	disclaimerPop.find("li").removeClass("selectedDisc");
	if (objName != "") disclaimerPop.find("li."+ objName).addClass("selectedDisc");
	
	if (arguments.length > 1) pageTitle = arguments[1]+' ';
	else if (objName != "") pageTitle = objName.replace("disc",'').replace(/([a-z])([A-Z])/g,"$1 $2")+' ';
	
	var discWindow = window.open("","DisclaimerWindow","height="+pageHeight+",width=640,scrollbars=1,left=250,top=150,directories=no,titlebar=no,toolbar=no,menubar=no");
	discWindow.document.write('<html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /><style type="text/css">');
	discWindow.document.write(
	    'body { font: 12px Tahoma,Verdana,Arial,Helvetica,sans-serif; color: #333; } '+
	    '#wrap { width: 96%; margin: 0 auto; }&#13; '+
	    '.popDiv {  } '+
	    '.popDiv ul { padding: 0; margin: 0; } '+
	    '.popDiv ul li { border: solid 1px #222; list-style-type: none; padding: 15px; padding-left: 35px; margin-bottom: 7px; font-size: 14px;} '+
	    '.discListSymb { margin-left: -25px; margin-right: 15px; width: 10px; height: 0px; display:inline-block; font-weight: bold; font-size: 100%; vertical-align: top; padding-top: 5px; } '+
	    '.selectedDisc { background-color: #AFDBFF; } '+
		'</style><body>'+
		'<div id="wrap">'+
		'<img style="float:right;height:50px;" src="/MMNA/images/blp/global_images/mitsu_logo.jpg" /> <br /> <br />'+
		'<h2>'+ pageTitle +'Disclaimer</h2>'
	);	
	//<div style="text-align: right;font-size: 120%">'+ (new Date().toDateString()) +'</div><br />
	discWindow.document.write(disclaimerPop.html());
	discWindow.document.write("<p>From: "+ document.location.href +"</p></div></body></html>");
	discWindow.document.close();
	discWindow.focus();
	// would be nice to have a scrollTo() in here
}


/*
 * Converts Array to Obj
 */
function arrayConverter(arr)
{
  var objTo = {};
  for(var i=0;i<arr.length;i++)
  {
	  objTo[arr[i]]='';
  }
  return objTo;
}


/*
 * Disclaimer Pop Up Javascript Builder/Controller
 * by Shawn (not completed by Shawn, - Joe)
 * 
 * This should be added to any page with disclaimers (globally) and any disclaimers on that page should
 *  have their symbols wrapped in an anchor with a class of popDisclaimer and their rel attribute set to
 *  the disclaimer key they relate to.  This will allow the disclaimer being clicked to be marked.
 *  
 * Any other triggers to the Disclaimer Page can just have the popDisclaimer class added to them
 * 
 * Eample usage:
 * 
 * <a href="#" class="popDisclaimer"  rel="Owner_Warranty09"   rev="1"  title="Owners Site" >  * </a> 
 * 
 * Here class should be "popDisclaimer" - REQUIRED
 * rel = 'Disclaimer Key' - REQUIRED
 * rev = Order number , the disclaimer should be displayed - OPTIONAL
 * title = using for page title - OPTIONAL
 */


// Initialize flashDisclaimers object, this should be redefined with any disclaimers that appear in Flash on the page
// Form should be "Disclaimer_Key": "Disclaimer Symbol", ie "Owner_Warranty": "&Dagger;"
// These will be added to the end of the disclaimer pop-list
var flashDisclaimers = {};

// This is the function that opens the Pop-Up window and fills in the Disclaimer HTML
function Disclaim(er) {
	// Remove any previously selected disclaimers
	disclaimerPop.find('li').removeClass('selectedDisc');
	
	// If this is a specific disclaimer click, mark it
	if(er.rel) { 
		disclaimerPop.find('li.'+er.rel).addClass('selectedDisc');
	}
	
	// Create Pop-up window... this needs to open a real page (this one doesn't exist and I didn't test it with IE yet) first to pass to, IE 7 gives Access Denied if it isn't passed a real blank page (ie  about:blank)
	var discWindow = window.open("about:blank", "_name", "width=800,height="+pageHeight+",scrollbars=1,screenX=250,screenY=150,directories=no,titlebar=no,status=no,toolbar=no,menubar=no");
	// Write out the new page in to the pop-up window
	discWindow.document.write('<html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><style type="text/css">');
	discWindow.document.write(
	    'body { font: 12px Tahoma,Verdana,Arial,Helvetica,sans-serif; color: #333; } '+
	    '#wrap { width: 85%; margin: 0 auto; }&#13; '+
	    '.popDiv {  } '+
	    '.popDiv ul { padding: 0; margin: 0; } '+
	    '.popDiv ul li { border: solid 1px #222; list-style-type: none; padding: 15px; padding-left: 35px; margin-bottom: 7px; font-size: 14px;} '+
	    '.discListSymb { margin-left: -25px; margin-right: 15px; width: 10px; height: 0px; display:inline-block; font-weight: bold; font-size: 100%; vertical-align: top; padding-top: 5px; } '+
	    '.selectedDisc { background-color: #AFDBFF; } '
	);
	
	var today = new Date();
	// Get Page Title, this variable should appear somewhere on the page to indicate the page title, otherwise defaults to a generic
	
	//set the title
	if ( er.title ) {
		pageTitle = er.title;
	}
	// <div style="text-align: right;font-size: 120%">'+today.toDateString()+'</div><br />
	discWindow.document.write(		
		'</style><body>'+
		'<div id="wrap">'+
		'<img style="float:right;height:50px;" src="/MMNA/images/blp/global_images/mitsu_logo.jpg" /> <br /> <br />'+
		'<h2>'+pageTitle+' disclaimer</h2>'
	);
	// Output HTML of object we created earlier
	discWindow.document.write(disclaimerPop.html());
	discWindow.document.write(
		'<p>From: '+document.location.href+'</p>'+
		'</div></body></html>'
	);
	discWindow.document.close();
	discWindow.focus();
}


// This is the function that opens the Pop-Up window and fills in the Disclaimer HTML
function flashDisclaimer(er) {
	// Remove any previously selected disclaimers
	disclaimerPop.find('li').removeClass('selectedDisc');
	
	// If this is a specific disclaimer click, mark it
	if(er.rel) { 
		disclaimerPop.find('li.'+er.rel).addClass('selectedDisc');
	}
	
	// Create Pop-up window... this needs to open a real page (this one doesn't exist and I didn't test it with IE yet) first to pass to, IE 7 gives Access Denied if it isn't passed a real blank page (ie  about:blank)
	var discWindow = window.open("about:blank", "_name", "width=800,height="+pageHeight+",scrollbars=1,screenX=250,screenY=150,directories=no,titlebar=no,status=no,toolbar=no,menubar=no");
	// Write out the new page in to the pop-up window
	discWindow.document.write('<html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><style type="text/css">');
	discWindow.document.write(
	    'body { font: 12px Tahoma,Verdana,Arial,Helvetica,sans-serif; color: #333; } '+
	    '#wrap { width: 85%; margin: 0 auto; }&#13; '+
	    '.popDiv {  } '+
	    '.popDiv ul { padding: 0; margin: 0; } '+
	    '.popDiv ul li { border: solid 1px #222; list-style-type: none; padding: 15px; padding-left: 35px; margin-bottom: 7px; font-size: 14px;} '+
	    '.discListSymb { margin-left: -25px; margin-right: 15px; width: 10px; height: 0px; display:inline-block; font-weight: bold; font-size: 100%; vertical-align: top; padding-top: 5px; } '+
	    '.selectedDisc { background-color: #AFDBFF; } '
	);
	
	var today = new Date();
	// Get Page Title, this variable should appear somewhere on the page to indicate the page title, otherwise defaults to a generic
	
	//set the title
	if ( er.title ) {
		pageTitle = er.title;
	}

	if(er.disclaimer){
		pageBody = er.disclaimer;
	}
	//<div style="text-align: right;font-size: 120%">'+today.toDateString()+'</div><br />
	discWindow.document.write(			
		'</style><body>'+
		'<div id="wrap">'+
		'<img style="float:right;height:50px;" src="/MMNA/images/blp/global_images/mitsu_logo.jpg" /> <br /> <br />'+
		'<h2>'+pageTitle+' disclaimer</h2>'
	);
	// Output HTML of object we created earlier
	discWindow.document.write(pageBody);
	discWindow.document.write(
		'<p>From: '+document.location.href+'</p>'+
		'</div></body></html>'
	);
	discWindow.document.close();
	discWindow.focus();
}


// This runs after the document is ready
/*
$(function() {
		                  
	// Performs AJAX post to given URL for JSON of disclaimer information
	var check_dup = new Object();  // Create new object to help with removing duplicate disclaimer listings from page
	// Grab each element with the clas popDisclaimer and add any disclaimers it represents to the disclaimer pop list
    $('.popDisclaimer').each(function() {
    	
    	if( this.rel) {
    		
    		// Check if it's a duplicate
	    	if(!(this.rel in check_dup) && this.rel != 'VIEW_ALL' ) {
	    		
	    		if( pageHeight < 550 ) {
	    			pageHeight = pageHeight + 150;
	    		}
	    		
	    		check_dup[this.rel] = true;
	    		
	    		var innerHTML = 'body_key_'+this.rel;
	    		
	    		$.getJSON("/MMNA/legalDisclaimerAction.do?disclaimerKey="+this.rel,function(data)
	     		{
	    			var bodyKey = "body_key_"+data.disclaimerKey;
	    			var htm = disclaimerPop.html();
	    			htm = htm.replace( bodyKey , data.body );
	    			disclaimerPop.html ( htm );
	     		});
	    		
	    		var phText = "ul";
	    		if( this.rev ) {
	    			phText = "div#"+ (this.rev - 1);
	    		} 
	    		
			    disclaimerPop.find(phText).append(
					     $('<li />').append(
					     	$('<sup />')
			            	.append(
					                $('<span />').html(this.innerHTML).addClass('discListSymb')
					        )).append(innerHTML).addClass(this.rel)
			    );  

		    	//set the title
		    	if ( this.title ) {
		    		pageTitle = this.title;
		    	}
	    	}
    	}
    }).click(function() {
    	// On Click, run this function
    	Disclaim(this);
    });
    
    // Add flash disclaimers to list
    $.each(flashDisclaimers, function(discId,discSymb) { 
    	disclaimerPop.find('ul').append(
            $('<li />').append(
            	$('<span />').html(discSymb).addClass('discListSymb')
            ).append(discHash[discId]).addClass(discId)
    	)
    })
});
*/
