/*
****************************************************************************
* Filename:   config.js
* Function:   TECHMATRIX
*              
* Created by:  Vincent Perlerin for WebFirst, Inc.
* Date:        2007
*
* Modification log:
* Author		Date		Modification
* ------		----		------------
*
****************************************************************************
*/

// Global Design Variable for Matrix
var	paddingLeft = 10;
var paddingRight = 10;
var paddingTop = 1;
var paddingBottom = 1;
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6  = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

var matrixBorderHori = 50;
var matrixBorderVert = 75;

// Confirm Box
var cookieValueRow    = "rConf";
var cookieValueCol 	  = "cConf";
var cookieValueScroll = "scrollConf";

// Number of Products on the Matrix before we display the Warning Message
var maxProductBeforeAlert = 50;
var cookieValueAlert = "maxProdConf";



//	alert(navigator.appName + " ====== " + navigator.userAgent);



/*****************************************************************************
* Bookmark
*****************************************************************************/
function bookmark(title, url) {
   if (window.sidebar) { 
        window.sidebar.addPanel(title, url,""); 
    } else if( document.all ) {
        window.external.AddFavorite( url, title);
    } else  {
        alert("Ctrl+D to bookmark");
	    return true;
    }

}




/*****************************************************************************
* Fixing #homePresentation div height on homepage
* Note: It doesn't apply for Apple
*****************************************************************************/
function homeFixing() {
		//	Except for Safari
		if(navigator.vendor!="Apple Computer, Inc.") {
		$('#homePresentation').height()>$('#homeSearch').height()?$('#homeSearch').css("height",$('#homePresentation').height()):$('#homePresentation').css("height",$('#homeSearch').height()-3); }
}



/*****************************************************************************
* Apply Menu 
*****************************************************************************/
function menu() {
		
		// Place down arrows on menu 
		// if has submenu
		$('a.top').addClass('subMenu');
		
		// MENU HOVER EFFECT when mouse over sub menu
		$('ul.nav li ul li a').each( function() {
							var object = 	$(this).parent().parent().parent().find("a.top");					   
							
							$(this).parent().parent().mouseover(function() {
								object.css("background","url(_graphics/_bullets/subMenuOn.gif)  no-repeat 100% 13px #fff" );
								object.css("color","#377bac" );	
							}),
							$(this).parent().parent().mouseout(function(){
								object.css("background","transparent url(_graphics/_bullets/subMenu.gif) no-repeat 100% 13px" );
								object.css("color","#fff" );	
							});
		 });
			
		 // Hover Effect on Menu Items 
		 $('ul.nav li a.top').each( function() {
							$(this).mouseover(function(){
								$(this).css("background","url(_graphics/_bullets/subMenuOn.gif)  no-repeat 100% 13px #fff" );
								$(this).css("color","#377bac" );	
							}),
							$(this).mouseout(function(){
								$(this).css("background","transparent url(_graphics/_bullets/subMenu.gif) no-repeat 100% 13px" );
								$(this).css("color","#fff" );	
							});
		 });
		 
		
		// Menu for IE=< 6
		if (  (jQuery.browser.msie && (ie55 || ie6)) ) {
 				 $("ul.nav").superfish();
		}	
		 
}




//**************************************************************************
// SHOW BUSYBOX
//****************************************************************************/
function showBusyBox(text) {
    if (!text)  text = "Processing...";
    $('#busybox #busyboxHeader').html(text);
	$('#busybox').css("height",$(document).height());
	$('#busybox').css("width",$(document).width());
	$('#busybox').show();
	$('#busybox').css("opacity","0.5");
}

function hideBusyBox() {
		$('#busybox').hide();
}


//**************************************************************************
// HIDE ROW IN MATRIX
//****************************************************************************/
function runhideRow(id) {
        $('#selectedFeatures').selectOptions(id,true);
        selectSome('selectedFeatures','availableFeatures');
        urlChanged();
		$('tr#feat'+id).remove();		   // HIDE ROW HEADER
		$('tr#feat'+id+'Row').remove();	   // HIDE ROW
		$('tr.sub'+id).remove();	   	   // HIDE ROW	
		stripes();					   	   // RESTRIPES 
		ResizeScrollArea();    // RESIZE SCROLLING AREA
		hideBusyBox();
		
}


// FUNCTION MATRIX 
// Hide a column and display busybox
function hideRow(id) {

	// READ COOKIE FIRST
	if($.cookie(cookieValueRow)==null || $.cookie(cookieValueRow)=="n") {
		$('#confirm')
			.jqmShow()
			.find('p.jqmConfirmMsg')
			.html("You are about to hide a feature from your Matrix.")
			.end()
			.find('p.jqmHelpMsg')
			.html("If you want to add this feature back to the Matrix, click 'Display/Hide Features'")
			.end()
			.find('input#cookie')
			.attr("checked", "") 
			;

        $('#yesCONFIRM').unbind();
        $('#noCONFIRM').unbind();
		$('#yesCONFIRM').click( function() { 
								 hideRowGo(id);
								 readCheck(cookieValueRow);
								 $('#confirm').jqmHide();
								 id=null; // IMPORTANT FOR MULTI-EVENTS 
								 }
		);

		$('#noCONFIRM').click( function() { 
								 $('#confirm').jqmHide();
								 id=null; // IMPORTANT FOR MULTI-EVENTS 
								 }
		);
		
		

	} else {
		 hideRowGo(id);
	}


}


// HIDE ROW AFTER CONFIRMATION 
function hideRowGo(id) {

	// Nb Row > 1 (2 with row for resize trick)
	if( $('#headerColumn table tr th div').length - $('#headerColumn table tr.subFeature th div').length> 1) {
		showBusyBox();
		window.setTimeout('runhideRow(\''+id+'\')',200);
	} else {
		alert("You cannot have less than one row in the Matrix");	
	}
}





//**************************************************************************
// HIDE COLUMN IN MATRIX
//****************************************************************************/
function runhideCol(id) {
        $('#selectedProducts').selectOptions(id,true);
        selectSome('selectedProducts','availableProducts');
        urlChanged();
		$('th.prod'+id).remove();	
		$('td.prod'+id).remove();
		ResizeScrollArea();
		resizeCornerAfterColDeletion();
		hideBusyBox();
}

function hideCol(id) {

	
	// READ COOKIE FIRST
	if($.cookie(cookieValueCol)==null || $.cookie(cookieValueCol)=="n") {
		// CONFIRM BOX 
		$('#confirm')
			.jqmShow()
			.find('p.jqmConfirmMsg')
			.html("You are about to hide a product from your Matrix.")
			.end()
			.find('p.jqmHelpMsg')
			.html("If you want to add this product back to the Matrix, click 'Display/Hide Products'")
			.end()
			.find('input#cookie')
			.attr("checked", "") 
			;

        $('#yesCONFIRM').unbind();
        $('#noCONFIRM').unbind();
		$('#yesCONFIRM').click( function() { 
								 hideColGo(id);
								 readCheck(cookieValueCol);
								 $('#confirm').jqmHide();
								 id=null; // IMPORTANT FOR MULTI-EVENTS 
								 }
		);

		$('#noCONFIRM').click( function() { 
								 $('#confirm').jqmHide();
								 id=null; // IMPORTANT FOR MULTI-EVENTS 
								 }
		);
	
	} else {
		 hideColGo(id);
	}
	

}


// FUNCTION MATRIX 
// Hide a column and display busybox
function hideColGo(id) {

	// Nb Col > 1  (2 with col for resize trick)
	if( $('#headerRow table tr th div').length > 1) {
		showBusyBox();
		window.setTimeout('runhideCol(\''+id+'\')',100);
	} else {
		alert("You cannot have less than one column in the Matrix");	
	}
}





//**************************************************************************
// READ CONFIRM CHECKBOX AND WRITE COOKIE
//****************************************************************************/
function readCheck(value) {
	// IF CHECKBOX IS CHECKED -> WRITE COOKIE "Y" 
	$('input#cookie').attr("checked")?$.cookie(value,"y",{expires:365}):$.cookie(value,"n",{expires:365});
}


//**************************************************************************
// SHOW/ HIDE SUB FEATURE 
//****************************************************************************/


function toggleSubFeature(id) {

    var btn = $('div#toggleSub'+id);
	btn.blur();
	if( $('tr.sub' + id).css("display") == 'none') {
		$('tr.sub' + id).show('');
		
		// Change Button Value
		btn.removeClass();
		btn.addClass("buttonCollapse");
		
	} else {
		$('tr.sub' + id).css('display','none');
		
		// Change Button Value
		btn.removeClass();
		btn.addClass("buttonExpand");
	}
	
	window.setTimeout(ResizeScrollArea, 500);

}

function goToContent() {
	location.hash = '#content';	
}

function expandAllFeatures(bool) {
	$('tr.subFeature').show();
	$('div.buttonExpand').removeClass().addClass("buttonCollapse");
	if(bool) {  window.setTimeout(ResizeScrollArea, 500); window.setTimeout(goToContent, 550);
	} 
}


function collapsedAllFeatures() {
	$('tr.subFeature').hide();
	$('div.buttonCollapse').removeClass().addClass("buttonExpand");
	window.setTimeout(ResizeScrollArea, 500);
	window.setTimeout(goToContent, 550);
}



/*****************************************************************************
* FORMAT MATRIX
*****************************************************************************/
function formatMatrix() {
	ScrollTable(50,75);
}


//**************************************************************************
// STRIPES THE MATRIX
//****************************************************************************/
function stripes() {
	
	var rowsHeader = $('table#headerColTable tr.toStripe');
	var rows	   = $('div#innerTable table.scrollTable tr.toStripe');
	
	var stripeClass1 = "alt";
	var stripeClass2 = "";
	var currentClassStripe = stripeClass2;	
	console.log($(rowsHeader).length);
	
	for(i=0;i<$(rowsHeader).length;i++) {

		
		currentRowHeader = $(rowsHeader[i]);
		currentRowHeaderClass = currentRowHeader.attr("class");
		
		currentRow	 = $(rows[i]);
		currentRowClass = currentRow.attr ("class");
		
		if(!isSubFeature(currentRowHeader)) {
			currentClassStripe = currentClassStripe==stripeClass1 ? stripeClass2 : stripeClass1;
		}

		currentRowHeader.removeClass(stripeClass1);
		currentRowHeader.addClass(currentClassStripe);
		currentRow.removeClass(stripeClass1);
		currentRow.addClass(currentClassStripe)
		
	}
}

function isSubFeature(currentRow) {
	    currentRowClass = currentRow.attr("class");
		return (currentRowClass!=null && (currentRowClass+"").indexOf("subFeature")>=0)?true:false;
}


/*****************************************************************************
* FIND POSITION OF AN OBJECT 
* (used to display modal divs)
*****************************************************************************/
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}


/*****************************************************************************
* SELECT MANIPULATION
* 
*****************************************************************************/




function selectSome(from,to) {
	$('#'+from).copyOptions('#'+to);
	$('#'+from).removeOption(/./, true);
}

function selectAll(from,to) {
	$('#'+from).copyOptions('#'+to,'all');
	$('#'+from).removeOption(/./);
}

// Move Up an Option
$.fn.moveUp = function()
{
	this.each(
		function() {
			var sel = new Array();
			for(var i=0; i < this.length; i++ )	if(this[i].selected) {
					if (this[i].selected == true) {
							sel[sel.length] = i;
					}	
			}
			
			for (var i=0; i < sel.length; i++ ) {
				if (sel[i] != 0 && !this[sel[i]-1].selected) {
					var tmp = new Array((document.body.innerHTML ? this[sel[i]-1].innerHTML : this[sel[i]-1].text), this[sel[i]-1].value);
					if (document.body.innerHTML) { this[sel[i]-1].innerHTML = this[sel[i]].innerHTML; }
					else 						 { this[sel[i]-1].text = this[sel[i]].text; }
					this[sel[i]-1].value = this[sel[i]].value;
					if (document.body.innerHTML) { this[sel[i]].innerHTML = tmp[0]; }
					else 						 { this[sel[i]].text = tmp[0]; }
					this[sel[i]].value = tmp[1];
					this[sel[i]-1].selected = true;
					this[sel[i]].selected = false;
				}
			}
		}
	);
}



// Move Down an Option
$.fn.moveDown = function()
{
	this.each(
		function() {
			var sel = new Array();
			
			for (var i=this.length-1; i>-1; i--) {
					if (this[i].selected) {
							sel[sel.length] = i;
					}
			}
			
			
			for (var i=0; i < sel.length; i++ ) {
				if (sel[i] != this.length-1 && !this[sel[i]+1].selected) {
					var tmp = new Array((document.body.innerHTML ? this[sel[i]+1].innerHTML : this[sel[i]+1].text), this[sel[i]+1].value);
					if (document.body.innerHTML) {this[sel[i]+1].innerHTML = this[sel[i]].innerHTML;}
					else 						 {this[sel[i]+1].text = this[sel[i]].text;}
					this[sel[i]+1].value = this[sel[i]].value;
					if (document.body.innerHTML) { this[sel[i]].innerHTML = tmp[0]; }
					else 						 { this[sel[i]].text = tmp[0]; }
					this[sel[i]].value = tmp[1];
					this[sel[i]].id = tmp[5];
					this[sel[i]+1].selected = true;
					this[sel[i]].selected = false;
			   }
			}
		}
	);
}


/*****************************************************************************
* DISPLAY OPTIONS (divs) FROM A SELECT OBJECT
* 
*****************************************************************************/
$.fn.displayOptions = function()
{
	this.each(
		function() {
			var sel = new Array();
		
			for(var i=0; i < this.length; i++ )	{
					if(this[i].selected) { $('#'+this[i].value).show(); }
					else 			     { $('#'+this[i].value).hide(); }
			}
		}
	);
}


function funStuff()
{
	formatMatrix(); 						// FORMAT MATRIX

	
	// Show Manage Feature when click on a.manageFeaturetrigger
	$('div#manageFeature').Draggable({zIndex:4000,opacity:0.7,insideParent:true,handle:'.top h2'});	// DRAGABBLE
	// Impossible to use #top as draggable area because of a bug on IE6 and below
	linkPos = findPos($('a.manageFeaturetrigger')[0]);											// DIV POSITIONNING 
	$('div#manageFeature').css("top",linkPos[1]);												// DIV POSITIONNING - top
	$('div#manageFeature').css("left",$(window).width()/2 - getDimensions($('div#manageFeature')[0]).width/2 - 10);	// DIV POSITIONNING - left
	$('div#manageFeature').jqm({trigger: 'a.manageFeaturetrigger', modal: true, onHide: revertFeatures}); 				// MODAL 
	// , onShow: cacheFeatures

	// Show Manage Feature when click on a.manageFeaturetrigger
	$('div#manageProduct').Draggable({zIndex:4000,opacity:0.7,insideParent:true,handle:'.top h2'});	// DRAGABBLE
	// Impossible to use #top as draggable area because of a bug on IE6 and below
	linkPos = findPos($('a.manageProducttrigger')[0]);											// DIV POSITIONNING 
	$('div#manageProduct').css("top",linkPos[1]);												// DIV POSITIONNING - top
	$('div#manageProduct').css("left",$(window).width()/2 - getDimensions($('#manageProduct')[0]).width/2 - 10);	// DIV POSITIONNING - left
	$('div#manageProduct').jqm({trigger: 'a.manageProducttrigger', modal: true, onHide: revertProducts}); 				// MODAL 
	// , onShow: cacheProducts


	// Show confirmation when click on an x
	$('div#confirm').Draggable({zIndex:4000,opacity:0.7,insideParent:true,handle:'.top h2'});	// DRAGABBLE
	$('div#confirm').css("top",linkPos[1]);														// DIV POSITIONNING - top
	$('div#confirm').css("left",$(window).width()/2 - getDimensions($('#manageProduct')[0]).width/2 - 10);			// DIV POSITIONNING - left		
	
	expandAllFeatures(false);
	resizeCornerAfterColDeletion();
	hideBusyBox();
	if(location.hash) location.hash = location.hash;
	
	

		// DO WEIRD THING IF SAFARI 2.0 or LESS
		 if(  (navigator.userAgent.indexOf("Version") == -1) &&  (navigator.userAgent.indexOf("Safari") !=-1 )) {
				collapsedAllFeatures();
				window.setTimeout('expandAllFeatures(false)', 500);
		 }


	
}

/*****************************************************************************
* SETUP MATRIX FUNCTIONNALITIES AND DESIGN TRICKS
* 
*****************************************************************************/
function setUpMatrix() {
		
    showBusyBox("Working...");
	setTimeout(funStuff, 200);


	cacheProducts();
	cacheFeatures();
	
	$('#bookmark').click(addBookmark);
	$('#yesFeat').click(loadFromLists);
	$('#yesProd').click(loadFromLists);

	urlChanged();
	$('#originalMatrix').attr('href', unescape(originalUrlQuery().substr(6)));
}

var mailToTemplate;
var pageName = "NCTI TechMatrix"; 

function addBookmark()
{
    var url = getUrl();
    var title = pageName;
    if (window.sidebar) { 
        window.sidebar.addPanel(title, url,""); 
    } else if( document.all ) {
        window.external.AddFavorite( url, title);
    } else if( window.opera && window.print ) {
        return true;
    }
}
function urlChanged()
{
	$('#sendToAFriend').attr('href', mailToTemplate.replace(/XYZZY/g, escape(getUrl())));
	$('#print').attr('href', 'matrixPrint.aspx' + getFragment());
	$('#lnkRelatedResearch').attr('href', 'relatedResearch.aspx' + getFragment(false));
}

// Reload the page based on the contents of the select boxes in the dialogs
function loadFromLists()
{
	if ($('#selectedProducts')[0].options.length==0) 
	{ 
	    alert("You cannot have zero products in the Matrix");
	    return false;
	}
	else if ($('#selectedFeatures')[0].options.length==0)
	{
	    alert("You cannot have zero features in the Matrix");
	    return false;
	}
    showBusyBox("Loading...");
   	location.href = getFragment(true, true) + '#content';
   	return true;
}

function getUrl()
{
    return location.href.match(/^([^?]*)/)[1] + getFragment(true);
}

function originalUrlQuery()
{
    var orig = location.href.match(/(&orig=[^&#]*)/);
    orig = orig ? orig[1] : "&orig=" + escape(location.href);
    return orig;
}

function getReferrer()
{
    var ref = location.href.match(/(&ref=[^&#]*)/);
    ref = ref ? ref[1] : "&ref=" + escape(document.referrer);
    return ref;
}

function getFragment(includeOriginal, includeReferrer)
{
    var loc = '?';
    var s  = location.href.match(/[?&](s=(?:\d+)(?:,\d+)*)/);
    var ls = location.href.match(/(&?ls=(?:\d+)(?:,\d+)*)/);
    if (s) loc += s[1];
    if (ls) loc += ls[1];
    loc += '&p=' + $.map($('#selectedProducts')[0].options, function (opt){ return opt.value;}).join(",") +
        '&f=' + $.map($('#selectedFeatures')[0].options, function (opt){ return opt.value;}).join(",") + 
        (includeOriginal ? originalUrlQuery() : "") +
        (includeReferrer ? getReferrer() : "");
    return loc;
}

function revertFeatures(h)
{
    revertSelection(h, 'availableFeatures','selectedFeatures');
}
function revertProducts(h)
{
    revertSelection(h, 'availableProducts','selectedProducts');
}

function revertSelection(h, from, to)
{
    h.w.hide();
    h.o.remove();
    window.setTimeout('reallyRevertSelection(\'' + from + '\',\'' + to + '\')', 50);
}
function reallyRevertSelection(from, to)
{
    var sFrom = $('#'+from);
    var sTo = $('#'+to);
    for (var i=0, cache = sFrom[0].thecache, len=cache.length; i<len; ++i)
    {
        sTo.selectOptions(cache[i], true);
        selectSome(to, from);
    }
    for (var i=0, cache = sTo[0].thecache, len=cache.length; i<len; ++i)
    {
        sFrom.selectOptions(cache[i], true);
        selectSome(from, to);
    }
}

function cacheProducts()
{
    cacheOptionValues(['#availableProducts','#selectedProducts']);
    return true;
}

function cacheFeatures()
{
    cacheOptionValues(['#availableFeatures', '#selectedFeatures']);
    return true;
}

function cacheOptionValues(list)
{
    $.each(list, function(i, id) {
        var select = $(id)[0];
        select.thecache = [];
        for (var i=0,len=select.options.length; i< len ; ++i)
            select.thecache[i] = select.options[i].value;
    });
}


/*****************************************************************************
* Fixing #footer
*****************************************************************************/
function footerFixing() {
	
	var pad=0;
	jQuery.browser.msie?pad=0:pad=20;
	
	if($(window).height()-$('#primary-content-wrapper').height()-$('#footer-wapper').height()>0) {
		$('#primary-content-wrapper').css("padding-bottom",$(window).height()-$('#primary-content-wrapper').height()-$('#footer-wapper').height()-pad+"px");
	}
	

	
}


/*****************************************************************************
* SHOW ALERT MESSAGE IF NUMBER OF PRODUCT IN MATRIX TO GENERATE > maxProductBeforeAlert
* number of products to display / links for div positioning
*****************************************************************************/
function showAlertMaxProduct(numberOfProduct,pos) {
		
			// ALERT MESSAGE 
			$('div#confirm').Draggable({zIndex:4000,opacity:0.7,insideParent:true,handle:'.top h2'});	// DRAGABBLE
			$('div#confirm').css("top",250);		// DIV POSITIONNING - top (250 because of IE amd LACK of time)
			$('div#confirm').css("left",810/2-300);		// DIV POSITIONNING - left		(810 because of IE amd LACK of time)
			$('div#confirm').jqm({modal: true}); 

			$('div#confirm').jqmShow().find('span#magicNumber').html(numberOfProduct).end().find('input#cookie').attr("checked", "checked");
		
			$('#yesCONFIRM').click( function() { 
											 readCheck(cookieValueAlert);
											 $('#confirm').jqmHide();
											 $('#goMatrix').attr("value","go");
											 $('#ctl00_cntMain_btFind').click();
											 return true;
				}
			);
			
			$('#noCONFIRM').click( function() { 
											 $('#confirm').jqmHide();
											 $('#goMatrix').attr("value","dontgo");
											 return false;							 
				}
			);
			
		
}

/*****************************************************************************
* When Document is Loaded 
*****************************************************************************/
$(function() {	


	// Set-up Menu 
	menu();
	
	// FIX DESIGN ON HOMEPAGE
	if($("body").attr("id")=="home") {	 
		homeFixing(); 				// Uniformization of the Height on the homepage
		$(document).pngFix(); 		// PNG Trasnparency for IE 6<=

	}
	
	// SET-UP THE MATRIX 
	if($("body").attr("id")=="matrix") {	 
	 	// SET-UP CONFIRM BOXES
		 $('#confirm').jqm({overlay: 50, modal: true});
		 setUpMatrix();
	 
	} else {
		footerFixing();
	}
	
	
	
	// ToolTips 
	document.onmousemove=positiontip;
	addwarning();
	

	
});

