var loadTimer = null;

Number.prototype.roundToPrecision = function( precision ) {
	if (precision===undefined) { precision = 2; }
  	var multiplier = Math.pow(10,precision);
  	return Math.round(this*multiplier)/multiplier; 
}
Number.prototype.ensureDecimalPlaces = function( decimals ) {
  	var tempString = this.toString(),
		pileOfPads = "000000000000000000000000",
		decimalLocation = tempString.indexOf('.');
  	if (decimalLocation === -1) {
    	retVal = tempString + '.' + pileOfPads.substring(0,decimals);
  	} else {
    	retVal = tempString + pileOfPads;
    	retVal = retVal.substring(0,decimalLocation+decimals+1);
  	}
  	return retVal;  
}


function meezyDate( aDate ) {
	var MONTHS     = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
  	var month  = aDate.split('/')[0],
      	days   = aDate.split('/')[1],
      	year   = aDate.split('/')[2],
      	retVal = MONTHS[parseInt(month)-1] + ' ' + days + ', ' + year;
  return retVal; 
}
function fetchStockValue() {
	var oRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : null,
		theURL   = 'meezy.php'; 
	if (oRequest) {
	    oRequest.open('GET', theURL);
	    oRequest.onreadystatechange = function(event) {
		  	if (this.readyState===4) {
            	if (this.status===200) {
	 	      		var stockQuote = oRequest.responseText.replace(/("| |\s)/gi,'').split(','),    // This strips out all whitespace and converts it into an array
						theDate             = stockQuote[0],
              			theFundName         = stockQuote[1],
              			thePrice            = stockQuote[2],
             			theDollarChange     = stockQuote[3],
						theYTDPercentChange = stockQuote[4],
			 			yesturdayValue      = thePrice - theDollarChange,
              			thePercentChange      = ((theDollarChange/yesturdayValue)*100).roundToPrecision(2).ensureDecimalPlaces(2) + '%';
              					
			  		document.getElementById('stock_price').innerHTML      		= '$' + thePrice;
			  		document.getElementById('myDate').innerHTML              	= meezyDate(  theDate );
			
				  	if (parseFloat(theYTDPercentChange) >= 0) {
						document.getElementById('stock_percent_change_ytd').className  = "positive";
						document.getElementById('stock_percent_change_ytd').innerHTML = '&#43;' + theYTDPercentChange;
				  	} else {
					 	document.getElementById('stock_percent_change_ytd').className  = "negative";
						
					 	document.getElementById('stock_percent_change_ytd').innerHTML = theYTDPercentChange.replace("-","&ndash; ");
				  	}
				  	
				  	if (parseFloat(theDollarChange) >= 0) {
						document.getElementById('stock_percent_change').className = "positive";
						document.getElementById('stock_dollar_change').className  = "positive";
						document.getElementById('stock_percent_change').innerHTML     = '&#43;' + thePercentChange;
						document.getElementById('stock_dollar_change').innerHTML      = '&#43;&#36;' + theDollarChange;
				  	} else {
						document.getElementById('stock_percent_change').className = "negative";
						document.getElementById('stock_dollar_change').className  = "negative";
						
						
						document.getElementById('stock_percent_change').innerHTML = thePercentChange.replace("-","&ndash; ");
						document.getElementById('stock_dollar_change').innerHTML  = theDollarChange.replace("-","&ndash;&#36; ");
				  	}
		    	} else {
		      		alert("There was an error retrieving the quote");	
		    	}
		  	}
	    }	
	    oRequest.send(null);
	} else {
	    alert("This browser does not support Ajax, Jackson.")	
	}
}

var BerkShire = {
	pageFlipper : {
    _default : {
		bgURLS : [ "images/hm/pic_1.jpg", "images/hm/pic_2.jpg", "images/hm/pic_3.jpg", "images/hm/pic_4.jpg", "images/hm/pic_5.jpg"]
    },
    _state : {
      currentPage : 0,
      fadedInTarget  : 'fader_1',
      fadedOutTarget : 'fader_2'
    },
    init : function( ) {
	  	this._state.currentPage = 0;

      	for (var i=0,iEnd=this._default.bgURLS.length;i<iEnd;i++) {  // Cache images by pre-loading them
        	var imgCache = document.createElement('img');
        	imgCache.src = this._default.bgURLS[ i ];
      	}
    },
    display : function() {
      	var targetToFadeOut = this._state.fadedInTarget,
          	targetToFadeIn  = this._state.fadedOutTarget;
      	this.setOpacity(targetToFadeOut,100);   // Just to be sure ... not really necessary
      	this.setOpacity(targetToFadeIn,0);      // Just to be sure ... not really necessary
      	document.getElementById(targetToFadeIn).style.backgroundImage = "url('" + this._default.bgURLS[ this._state.currentPage ] + "')";
      	this.fadeOut(targetToFadeOut,1000);
      	this.fadeIn(targetToFadeIn,1000);
      	this._state.fadedInTarget  = targetToFadeIn;
      	this._state.fadedOutTarget = targetToFadeOut;
    },
	
    fadeIn : function( oHTMLElementID, duration ) {
      	var speed = Math.round(duration / 100),
          	timer = 0;
      	for (var i=0,iEnd=100;i<=iEnd;i++) {
        	setTimeout("BerkShire.pageFlipper.setOpacity('" + oHTMLElementID + "'," + i + ")", timer * speed);
        	timer++;
      	}
    },
    fadeOut : function( oHTMLElementID, duration ) {
      	var speed = Math.round(duration / 100),
          	timer = 0;
      	for (var i=100,iEnd=0;i>=iEnd;i--) {
        	setTimeout("BerkShire.pageFlipper.setOpacity('" + oHTMLElementID + "'," + i + ")", timer * speed);
        	timer++;
      	}
    },
    next : function() {
      	this._state.currentPage += 1;
      	this._state.currentPage = this._state.currentPage % this._default.bgURLS.length;
      	this.display();
    },
    previous : function() {
      	this._state.currentPage -= 1;
      	if (this._state.currentPage < 0) { this._state.currentPage = this._default.bgURLS.length-1 };
      	this.display();
    },
    setOpacity : function( oHTMLElement, opacity ) {
      	if (typeof(oHTMLElement)=="string")  { oHTMLElement = document.getElementById(oHTMLElement); }
      	oHTMLElement.style.opacity = opacity / 100;
      	oHTMLElement.style.filter  = 'alpha(opacity=' + opacity + ')';
    }
  } // pageFlipper END
}
function setup() {
	fetchStockValue();
  	BerkShire.pageFlipper.init();
}
function testIfSliderOpened() {
  var oSlider = document.getElementById('stockticker');
  if (parseInt(oSlider.style.left) === 0) { 
    //alert('already expanded. Not doing nothing!'); 
  } else {
	//alert('collapsed');
	slideStock();
  }
}
function setArrowImage( imageURL ) {
  var oArrow2 = document.getElementById("arrowImg");
  oArrow2.src = imageURL;
}
function slideStock () {
		var oArrow = document.getElementById("arrowImg");
		$("#stockticker").fadeIn();
		
		if(oArrow.src.indexOf("arrow_left.jpg") > -1) {  // Open, closing
		  setTimeout("setArrowImage('images/arrow.jpg')",1000);
			//oArrow.src = "images/arrow.jpg";
			$("#stockticker").animate({"left": "-550px"},1000);
		} else {
		  setTimeout("setArrowImage('images/arrow_left.jpg')",1000);
			// oArrow.src = "images/arrow_left.jpg";        //Closed, opening
			$("#stockticker").animate({"left": "0px"},1000);
	  	    $('#main-navigation li').not($(this)).removeClass('active').find('.dropdown').fadeOut();
		}
		
	
	 return false;	
	}

$(document).ready(function() {
	$("#stockticker").animate({"left": "0px"},1000);
	//loadTimer = setTimeout(function() { testIfSliderOpened(); }, 10000);
	
	/*$('#main-navigation li').hover(function() {
		$(this).addClass('hover');
		$(this).find('.dropdown').stop(true, true).fadeIn();
		$('#stockticker').stop(true, true).fadeOut();
	}, function() {
		$(this).removeClass('hover');
		$(this).find('.dropdown').stop(true, true).fadeOut();
		$('#stockticker').stop(true, true).fadeIn();
	});*/ 	
	
	$('#main-navigation li').hover(function() {
		$(this).addClass('hover');
		/*if ($(this).hasClass('active')) {	
		} else {
			$(this).find('.dropdown').stop(true, true).fadeIn();
			$('#stockticker').fadeOut();
			$("#stockticker").animate({"left": "-550px"},1000);
			document.getElementById("arrowImg").src = "images/arrow.jpg";
		};*/
	}, function() {
		$(this).removeClass('hover');
		/*if ($(this).hasClass('active')) {
		} else {
			$(this).find('.dropdown').stop(true, true).fadeOut();
			//loadTimer = setTimeout(function() { testIfSliderOpened(); }, 10000);
			return false;
		};*/
	});
	
	$('#main-navigation li').live('click', function() {
		$('#main-navigation li').not($(this)).removeClass('active').find('.dropdown').hide();
		$(this).toggleClass('active');
		if ($(this).find('.dropdown').length) {
			if ($(this).hasClass('active')) {
				$(this).find('.dropdown').show();
				$('#stockticker').fadeOut();
				$("#stockticker").animate({"left": "-550px"},1000);
				document.getElementById("arrowImg").src = "images/arrow.jpg";
			} else {
				$(this).find('.dropdown').hide();
				//slideStock ();
			};	
			return false;
		} else {
			return true;
		};
	});
});
