// Mini Matrix

var changeAlert = false;
var running = false;
var reinitialiseScrollPane = function(){$('#mmScroll').jScrollPane({showArrows:true, scrollbarWidth:10, scrollbarMargin:0});}

function updateMatrix(cnid, cur, cid) {
	if (running == true) return;
	$(loadingMMContent);
	running = true;
	$.ajax({
	  url: '/miniMatrix',
	  type: "GET",
	  data: "cnid=" + cnid + "&cur=" + cur + "&cid=" + cid,
	  success: function(data) {
		$('#miniBox').html(data);
		if (changeAlert) {
			$.fn.colorbox.init();
			$.fn.colorbox({width:"400px", inline:true, href:"#noProductAlert"});
		}
		//$(reinitialiseScrollPane);
		initPageEvents(-1);
		running = false;
	  }
	});	
}

function loadingMMContent() {
	$('#miniMatrixView').hide();
	$('#mmFootTable').hide();
	$('#mmFootMiddle').hide();
	$('#mmFootTableBlank').show();
	initScrollBars();
	$('#miniMatrixLoader').show();
}

function showNoProducts() {
	$.fn.colorbox.init();
	$.fn.colorbox({width:"400px", inline:true, href:"#noProductAlert"});
}

function showInfo(type, data) {
	var product = JSON.parse(data);
	var priceType = '';
	var arrowDirection = 'Null';
	var compareText = '';
	var range = '';
	var textCalc = 'This price was found in 1 Store';
	var shoppingLightHeader = '';
	$('#productName').html(product.productNameLong);
	$('#productDescription').html(product.productDescLong);
	$('#defaultCountry').html(product.defaultCountryName);	

	if (type == 'max') {
		var key = 'max';
		var arrowDirection = 'Up';
		var textArrow = '\&uarr\;';
		var lessMore = 'more';
		var range = 'Highest';
		var priceStatus = 'Highest Price For The ' + product.productNameLong + ' - ' + product.productDescLong;
	} else if (type == 'min'){
		var key = type
		var arrowDirection = 'Down';
		var textArrow = '\&darr\;';
		var lessMore = 'less';
		var range = 'Lowest';
		var priceStatus = 'Lowest Price For The ' + product.productNameLong + ' - ' + product.productDescLong;
	}
	
	var compareText = 'Price ' + (product[key + 'Compare']) + '% ' + lessMore + ' than ' + product.defaultCountryName;
	
	if (type == 'ref'){
		var key = 'default';
		var priceStatus = 'Reference Price';
		var textCalc = 'Choose another Country or Category to compare more prices.';
		textArrow = '';
		$('#defaultCountry').html('');
		if (product.avgPrice > product.defaultPrice) {
			var lessMore = 'less than ';
			var arrowDirection = 'Down';
		}else {
			var lessMore = 'more than ';
			var arrowDirection = 'Up';
		}
		var compareText = 'Price ' + product.defaultCompare + '% ' + lessMore + ' the average price';
	}
	
	if ((product[key + 'Cnt']) > 1) {
			var textCalc = range + ' Price Found in ' + (product[key + 'Cnt']) + ' Countries ' + (product[key + 'MultiCountryNames']);
		}
		
	if ((product[key + 'Compare']) < 1) {
		var arrowDirection = 'Null';
		if (product.defaultCountryId != (product[key + 'CountryId'])) {
			var compareText = 'same price as ' + product.defaultCountryName;
		}
	}

	var marq1 = 'Shopping Light \<span style\=\"background\-color\:';
	var marq2 = '\;width\:10px\;\"\>\&nbsp\;&nbsp\;&nbsp\;&nbsp\;\<\/span\> ';
	var marqGreen = '\(GREEN\) Buy Now! No imminent changes in this product category.';
	var marqYellow = '\(Yellow\) product category change expected.'
	var marqRed = '\(RED\) product category change is imminent.'
	
	if (product.shoppingLight == 1) {
		var shoppingLightHeader = marq1 + '\#00CC00' + marq2 + marqGreen;
	}else if (product.shoppingLight == 2) {
		var shoppingLightHeader = marq1 + '\#FFFF66' + marq2 + marqYellow;
	}else if (product.shoppingLight == 3) {
		var shoppingLightHeader = marq1 + '\#CC0000' + marq2 + marqRed;
	}

//$('#currencySymbol').html(product.currencySymbol);
	var currencySymbol = (product.currencySymbol);
	var price = (product[key + 'Price']);
	var cycleMain = currencySymbol + ' ' + price + ' - ' + priceStatus;
	var currencySymbolOrg = (product.defaultcurrencySymbolOrg);
	var priceOrg = (product[key + 'PriceOrg'])
	var cycleCompare = textArrow + ' ' + compareText;
	var cycleOrgPrice = 'Actual Store Price: ' + currencySymbolOrg + ' ' + priceOrg;


//	$('#price').html(product[key + 'Price']);
//	$('#currencySymbolOrg').html(product[key + 'CurrencySymbolOrg']);
//	$('#priceOrg').html(product[key + 'PriceOrg']);
	$('#country').html(product[key + 'CountryName']);
	$('#countryFlag')[0].src='images/flags/SquareFlags/' + (product[key + 'CountryCode']) + '.png';
//	$('#arrow')[0].src='images/arrow' + arrowDirection +'.gif';	
	$('#infoText').html(textCalc);
	$('#shoppingLightHeader').html(shoppingLightHeader);
//	$('#compare').html(compareText);
	$('#productDisplay').show();
	//$('div.topMarquee marquee').marquee();
	$('#mmLabel').hide();
	$('#cycleMain').html(cycleMain);
	$('#cycleCompare').html(cycleCompare);
	$('#cycleOrgPrice').html(cycleOrgPrice);
}
/*
function highlightSelectedCountry() {
	$('#mmLocationSelect td.hoverSelect').removeClass('hoverSelect');
	$('#mmLocationSelect input.country:checked').parent().addClass('hoverSelect');
	$('#mmLocationSelect input.currency:checked').parent().addClass('hoverSelect');
}

function highlightSelectedCurrency() {
	$('#mmLocationSelect td.hoverSelect').removeClass('hoverSelect');
	$('#mmAddCurrencySelect td.hoverSelect').removeClass('hoverSelect');
	$('#mmLocationSelect input.country:checked').parent().addClass('hoverSelect');
	$('#mmLocationSelect input.currency:checked').parent().addClass('hoverSelect');
	$('#mmAddCurrencySelect input.currency:checked').parent().addClass('hoverSelect');
}

function highlightSelectedCategory() {
	if ($('#mmCategoriesView div.hoverSelect').length > 0)
		$('#mmCategoriesView div.hoverSelect').removeClass('hoverSelect');
	if ($('#mmCategoriesView td.hoverSelect').length > 0)
		$('#mmCategoriesView td.hoverSelect').removeClass('hoverSelect');
	
	var elt = $('#mmCategoriesView input:checked')[0];
	if (elt.value == -1 || elt.value == 0) {
		$('#mmCategoriesView input:checked').parent().addClass('hoverSelect');
	} else {
		$('#mmCategoriesView input:checked').parent().parent().parent().addClass('hoverSelect');
	}	
}
*/

function hideInfo() {
	$('#mmLabel').show();
	$('#productDisplay').hide(); 
}

function alertCheck() {
	var enable = $('#alertStatus')[0].checked == true ? 1 : 0;
	$.ajax({
	  url: '/miniBox/productAlert',
	  type: "GET",
	  data: "enable=" + enable,
	  success: function(data) {
		//$.fn.colorbox.close();
	  }
	});	
}

function hideNotification(event, name) {
	$("#"+name).hide();
	event.stopPropagation();
}

function initEZTooltip () {

	$(".tooltip-target").ezpz_tooltip({
		contentPosition: 'rightStatic',
		stayOnContent: true,
		offset: 30
	});
}

/*function initHover() {
	$('.hoverLink').hover(
		// in function
		function(){
			var id = $(this)[0].id;
			idParts = id.split('-');
			showInfo(idParts[0], infos.get(id));
		},
	 	// out function
		function() {
			hideInfo();
		}
	);
}*/

function initHover() {
	$('.hoverLink').hoverIntent({
		over: 
		// in function
		function(){
			var id = $(this)[0].id;
			idParts = id.split('-');
			showInfo(idParts[0], infos.get(id));
		},
	 	timeout: 100,
		interval: 200,
		sensitivity: 300,
		out:
		// out function
		function() {
			hideInfo();
		}
	});
}

var initTxt;
var initElt;
function initDropDownSelect() {
	$(".dropdown dt a").click(function(evt) {
		initElt = evt.currentTarget;
		initTxt = evt.currentTarget.innerHTML;
		var dropID = $(this).closest("dl").attr("id");
		var divs = $(".dropdown dd");
		var targetId = $('#' + dropID + ' dd')[0].id;
		$.each(divs, function(i, elt) {
			if (elt.id != targetId) {
				$("#"+elt.id+" ul").hide();
			}
		});
		$("#"+dropID+" dd ul").slideToggle(200);
		return false;
	});
	$(".dropdown dd ul li a").hover(function() {
		var dropID = $(this).closest("dl").attr("id"); 
		var textCode = $(this).text();
		var textCurName = '';
		if ($(this).hasClass('currencySelect')) {
			textCurName = ' - ' + $(this)[0].title;
		}
		var textCurShow = textCode + textCurName; 
		$("#"+dropID+" dt a").html(textCurShow); 
	}); 	
	$(".dropdown dd ul li a").click(function() {
		var dropID = $(this).closest("dl").attr("id"); 
		var text = $(this).html(); 
		var selVal = $(this).find(".dropdown_value").html(); 
		$("#"+dropID+" dt a").html(text); 
		$("#"+dropID+" dd ul").hide(); 
		return false;
	}); 
  	$('.dropdowndiv').mouseleave(function() {
		var elt = $(this)[0];
		$('#' + elt.id + ' ul').hide();
		initElt.innerHTML = initTxt;
	});
}

function initMarqueeCycle() {
	$('#marqueeCycle').cycle({ 
	    fx: 'zoom',
		delay: -1000,
		speed: 1500
		//timeout: 3500
	});	
}

function initCloudCycle() {
	$('#cloudCycle').cycle({ 
       fx:     'blindX',
       speed:   2000,
       timeout: 13000
       //delay:  -8000
    });
}

function initScrollBars() {
	$('#mmScroll').jScrollPane({showArrows:true, scrollbarWidth:10, scrollbarMargin:0});			
	$('#add-category').bind('click',function(){$(reinitialiseScrollPane);});
	$('#add-country').bind('click',function(){$(reinitialiseScrollPane);});
	$('#remove-category').bind('click',function(){$(reinitialiseScrollPane);});
	$('#remove-category2').bind('click',function(){$(reinitialiseScrollPane);});
	$('#remove-country').bind('click',function(){$(reinitialiseScrollPane);});
	$('#remove-country2').bind('click',function(){$(reinitialiseScrollPane);});
	$('#remove-country3').bind('click',function(){$(reinitialiseScrollPane);});
	$('.add-notifications').bind('click',function(){$(reinitialiseScrollPane);});	
	$('#remove-notifications').bind('click',function(){$(reinitialiseScrollPane);});
}

$(document).ready(function(){
	initPageEvents(1);
});
		
function initPageEvents(isFirstLoad) {
	initEZTooltip();
	initScrollBars();
	initHover();
	initMarqueeCycle();
	initCloudCycle();
	initDropDownSelect();		
}

/*
	setInterval( "initcloudUpdate();", 10000 );
function initcloudUpdate() {
	$('#cloudGroup').load('miniMatrixCloud');
}
 */

/******************** hashmaps ********************/

function Map()
{
    // members
    this.keyArray = new Array(); // Keys
    this.valArray = new Array(); // Values
        
    // methods
    this.put = put;
    this.get = get;
    this.size = size;  
    this.clear = clear;
    this.keySet = keySet;
    this.valSet = valSet;
    this.showMe = showMe;   // returns a string with all keys and values in map.
    this.findIt = findIt;
    this.remove = remove;
}

function put( key, val )
{
    var elementIndex = this.findIt( key );
    
    if( elementIndex == (-1) )
    {
        this.keyArray.push( key );
        this.valArray.push( val );
    }
    else
    {
        this.valArray[ elementIndex ] = val;
    }
}

function get( key )
{
    var result = null;
    var elementIndex = this.findIt( key );

    if( elementIndex != (-1) )
    {   
        result = this.valArray[ elementIndex ];
    }  
    
    return result;
}

function remove( key )
{
    var result = null;
    var elementIndex = this.findIt( key );

    if( elementIndex != (-1) )
    {
        this.keyArray = this.keyArray.removeAt(elementIndex);
        this.valArray = this.valArray.removeAt(elementIndex);
    }  
    
    return ;
}

function size()
{
    return (this.keyArray.length);  
}

function clear()
{
    for( var i = 0; i < this.keyArray.length; i++ )
    {
        this.keyArray.pop(); this.valArray.pop();   
    }
}

function keySet()
{
    return (this.keyArray);
}

function valSet()
{
    return (this.valArray);   
}

function showMe()
{
    var result = "";
    
    for( var i = 0; i < this.keyArray.length; i++ )
    {
        result += "Key: " + this.keyArray[ i ] + "\tValues: " + this.valArray[ i ] + "\n";
    }
    return result;
}

function findIt( key )
{
    var result = (-1);

    for( var i = 0; i < this.keyArray.length; i++ )
    {
        if( this.keyArray[ i ] == key )
        {
            result = i;
            break;
        }
    }
    return result;
}

function removeAt( index )
{
  var part1 = this.slice( 0, index);
  var part2 = this.slice( index+1 );

  return( part1.concat( part2 ) );
}
Array.prototype.removeAt = removeAt;

