
//gets the prefix (test, dev, stage, gold, www) of the url
var thisLoc = location.host;
var sep = thisLoc.indexOf(".");
var pre = thisLoc.substr(0,sep);
//gets page user is on
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

//global vars declared
var itemPts = 0;
var userPts = 0;
var newUserPts = 0;
var cntId = 0;
var cntType = "";
var unlCnt = "";
var newUnlCnt = "";
var item;
var itemType;
/*---  make AJAX Request  ---*/
function checkPoints(_item){
    item = _item;
    cntId = item.substr(4);
    //check if item unlocked
    if($('#' + item).hasClass('locked')){
        getUserPts();
        displayPts();
        getCntPts();
        calcNewPts();
        // See if user has enough points to purchase item
        if(newUserPts==NaN || newUserPts==null || newUserPts<0){
            //display error message
            //jQuery.facebox('You do not have enough points to download this item.')
            openPopUp1();
            //dims screen (speed, opacity)
            //$.dimScreen(1000, 0.5);
        }else{        
            //unlock content
            //$('#' + item).removeClass('locked');
            //$('#' + item).addClass('unlocked')
            //alert('Content points: ' + itemPts); 
            
            //calls content lightbox
            openPopUp();
        }
    }else if($('#' + item).hasClass('unlocked')){
        //offer to download content again     
        //calls content lightbox
        openPopUp();
    }
}

/*---  make call to get new content opens lightbox  ---*/
function openPopUp1(){
    //send call to grab new div
    jQuery.facebox(function () {
        //for testing
//        jQuery.post('detail.html', function(data) {
//            jQuery.facebox('<div>' + data + '</div>')
//        })
        
        jQuery.post('http://' + pre + '.madballs.com/no_points.html', function(data) {
            jQuery.facebox('<div>' + data + '</div>')
        })
        //dims screen (speed, opacity)
        $.dimScreen(1000, 0.5);
    }) 
}

/*---  make call to get new content opens lightbox  ---*/
function openPopUp(){
    //send call to grab new div
    jQuery.facebox(function () {
        //for testing
//        jQuery.post('detail.html', function(data) {
//            jQuery.facebox('<div>' + data + '</div>')
//        })
        
        jQuery.post('http://' + pre + '.madballs.com/assetInfo.action?pre='+pre+'&assetId=' + cntId, function(data) {
            jQuery.facebox('<div>' + data + '</div>')
        })
        //dims screen (speed, opacity)
        $.dimScreen(1000, 0.5);
    }) 
}
/*---  Get user points  ---*/

function getUserPts(){
    //code to grab updated points from flash cookie
    //thisMovie("ScoreBoardUniversal").updateCookies();
    //code to get HTTP cookie
    userPts = getCookie('points');
    
	return userPts;
}
/*---  Get content points  ---*/
function getCntPts(){
    itemType = item.substr(0,4);
    //alert(itemType);
    if (itemType == "card"){
        //alert(cntId);
        var pts = '#points' + cntId.toString();
        //alert(pts);
        itemPts = $(pts)[0].value;
        //alert(itemPts);
    }else{
        itemPts = 0;
    }
    
}
/*---  Get unlocked content  ---*/
function getunlCnt(){
    //code to grab updated unlocked from flash cookie
    //thisMovie("ScoreBoardUniversal").updateCookies();
    //code to get browser cookie
    unlCnt = getCookie('unlockCnt');
}
/*--- Check if content is unlocked in cookie  ---*/
function chkCnt(){
    getunlCnt();
    var unlCntList = unlCnt.split(',');
    for(i=0; i < unlCntList.length; i++){
        var cnt = "card" + unlCntList[i];
        //alert(cnt);
        $('#' + cnt).removeClass('locked');
        $('#' + cnt).addClass('unlocked');
    }
    overlayLock();
};
/*---  Calculate new user points  ---*/
function calcNewPts(){
    //call to flash to deduct points
    //thisMovie("ScoreBoardUniversal").setDeductScore(itemPts);
    //call to set js cookie to new points value and set cookie
    //newUserPts = thisMovie("ScoreBoardUniversal").getPersonalScore();
    //updatePoints(newUserPts);
    
    //old js calculation
    newUserPts = userPts - itemPts;
    //alert(userPts + "-" + itemPts +"=" + newUserPts);
}
/*---  Add unlocked content  ---*/
function addUnlCnt(){
    //var testScore = thisMovie("ScoreBoardUniversal").updateCookies();
    //alert(testScore);
    thisMovie("ScoreBoardUniversal").setUnlockedContent(cntId);
    //update cookie with new content
    //unlCnt = thisMovie("ScoreBoardUniversal").getUnlockedContent();
    setCookie('unlockCnt', unlCnt, 365);
    
    
//    old js code
//    if(unlCnt == ""){
//        newUnlCnt = cntId;
//    }else{
//        newUnlCnt = unlCnt + cntId + "," ;
//    }
}


/*---  Updated Points Cookie in flash ---*/
function updatePoints(){
    thisMovie("ScoreBoardUniversal").setDeductScore(itemPts);
    //setCookie('points', pts, 365);
}

// Sets cookie
// accessed by passing it the name of the cookie and the value, and number of days(send 0 to not set expire attrib)
function setCookie (name, value, days) {
    if (days<1){
        // If an expiration date is not specifically defined, the cookies will expire at the end of the session (when the browser is closed)
        //alert("not setting expire date");
        document.cookie = name + '=' + value;
    }else{
        //alert("setting cookie: " + name + " = " + value + ", expires " + days);
        var today = new Date();
	    var expires = new Date( today.getTime() + (days * 1000 * 60 * 60 * 24) );
 	    document.cookie = name + '=' + value + "; expires=" + expires.toGMTString()+";";
    } 	
}
// Gets cookie
function getCookie( name ){
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}
// set default cookie for testing
//function testCookie(){
//    if(getCookie('points')==null){
//         setCookie('points', 150000, 365);   
//    }else{
//        //alert('User points: ' + getCookie('points'));
//    }
//    if(getCookie('unlockCnt')==null){
//        setCookie('unlockCnt', "0,", 365);
//    }else{
//        
//    }
//}
//changes cursor to hand.. for mouseovers on javascript links
function mouseHand()
{   
    document.body.style.cursor="pointer";
}
//changes cursor to default(pointer).. for mouseovers on javascript links
function mousePoint()
{
    document.body.style.cursor="default";
}

/*---  screen dimming plugin  ---*/
//by Brandon Goldman http://docs.jquery.com/Plugins/dimScreen
//useage:
//$.dimScreen(speed, opacity, callback);
//You can also stop the dimming:
//$.dimScreenStop(); 
jQuery.extend({
    //dims the screen
    dimScreen: function(speed, opacity, callback) {
        if(jQuery('#__dimScreen').size() > 0) return;
        
        if(typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if(typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if(speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }
        
        if(opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
        //ie hack to set height and width of window
        if($.browser.msie){
            var _height=( (jQuery(document).height() >= jQuery(window).innerHeight())? jQuery(document).height():jQuery(window).innerHeight())+'px'
        }else{
            var _height= $(document).attr('height') + 'px'
        }
        if ($.browser.msie){
            var _width=( (jQuery(document).width() <= jQuery(window).innerWidth())? jQuery(document).innerWidth():jQuery(window).width())+'px'
        }else{
            var _width= $(document).attr('width') + 'px'
        }
        return jQuery('<div></div>').attr({
                id: '__dimScreen'
                ,fade_opacity: opacity
                ,speed: speed
            }).css({
            height:_height
            ,width:_width    
            ,background: '#000'
            ,left: '0px'
            ,opacity: 0
            ,position: 'absolute'
            ,top: '0px'
            ,zIndex: 999
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },
    
    //stops current dimming of the screen
    dimScreenStop: function(callback) {
        var x = jQuery('#__dimScreen');
        var opacity = x.attr('fade_opacity');
        var speed = parseInt(x.attr('speed'), 10);
        if ($.browser.msie){
            var speed = parseInt(x.attr('speed'), 10);
        }else{
            var speed = x.attr('speed');
        }        
        x.fadeOut(speed, function() {
            x.remove();
            if(typeof callback == 'function') callback();
        });
    }
});
//closes lightbox
function closeDetail(){
    jQuery(document).trigger('close.facebox');
};
/*-- setup of carousel --*/
function setupCar()
{
    $('#carousel').Carousel(
	    {
		    itemWidth: 110,
		    itemHeight: 62,
		    itemMinWidth: 50,
		    items: 'span',
		    reflections: .5,
		    rotationSpeed: 1.8
	    }
    );
};
/*---  lock overlay  ---*/
function overlayLock(){
    var overlay = $('.overlay');
    var lockImage = $('.locked');
    var lockImageSrc = "images/Lock.png";
    var unlockImage = $('.unlocked');
    var unlockImageSrc = "images/blank.gif";
    
    if(lockImage.length > 0){
   	    for(var i=0; i<lockImage.length; i++){
   	        //alert(lockImage[i].id);
            overlay[i].style.display = 'block';
            // MSIE 5.x/6.x must be treated specially in order to make them use the PNG alpha channel
            if (lockImage.runtimeStyle)
                lockImage[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + lockImageSrc + "', sizingMethod='scale')";
            else
            lockImage[i].src = lockImageSrc;
            //alert('loaded LockDetail');
        }
    }
    if(unlockImage.length > 0){
        for(var i=0; i<unlockImage.length; i++){
            //alert(unlockImage[i].id);
            overlay[i].style.display = 'block';
            // MSIE 5.x/6.x must be treated specially in order to make them use the PNG alpha channel
            if (unlockImage.runtimeStyle)
                unlockImage[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + unlockImageSrc + "', sizingMethod='scale')";
            else
            unlockImage[i].src = unlockImageSrc;
            //alert('loaded LockDetail');
        }
    }
}

/*---  Display Total points  ---*/
function displayPts() {
    if (sPage=='downloads.html' || sPage=='content.action'){
        getUserPts();
        document.getElementById("totPts").innerHTML = userPts;
    }
};

/*--- Open the chance game in a facebox ---*/
function openChanceGame(){
	jQuery.facebox(function () {
    	jQuery.get('/chance.action', function(data) {
    		jQuery.facebox(data)
    	})
    	//dims screen (speed, opacity)
		setTimeout("$('#navigation').hide()", 1000); //wait a second!
		if (sPage=='about.action'){
		    $('#rust_wrapper').hide();
		}
    	$.dimScreen(1000, 0.5);
    }) 
}
/*--- Display Promos on the home page ---*/
function displayPromos()
{   //try to display from cookie.
	if( !displayPromoFromCookie() )
	{   //try flash
		var count = 0;
		var interval = window.setInterval(function (a,b) 
		{
	  		if(isReady())
	  		{
	  			displayPromosFromFlash()
	  			//breaks out of infinite loop
	  			count = 999; 
	  		}
	  		else
	  		{
				count++;
	  		}
	  		if(count > 4)
			{	//try at most 5 times
				clearInterval(interval);
			}
		},1000);
	}
};
/*--- Display Promo from HTTP Cookie if available ---*/
function displayPromoFromCookie()
{
	if(getCookie("teamId") != null)
	{
		flipPromos();
		return true;
	}
	else
	{
		return false;
	}
};
/*--- Display Promo from Flash cookie ---*/
function displayPromosFromFlash()
{	
	var team = getTeamId();
	if(!isNaN(team))
	{
		flipPromos();
		setCookie("teamId", team, 365);
		return true;
	}
	else
	{
		return false;
	}
};
/*--- Show/Hide Promos ---*/
function flipPromos()
{
	$("#mainPromo_team").show();
	$("#mainPromo_noteam").hide();
	
	$("#blockad_team").show();
	$("#blockad_noteam").hide();
};

/*--- hack for Firefox mouse click and stealing of image through link --*/
function whichButton(e)
{
    var tempItem
    // Handle different event models
    var e = e || window.event;
    var btnCode;
    var btnCode = e.button;
    if($.browser.mozilla){
        if(btnCode == 1){
            tempItem = 'detail' + cntId;
            buyContent(tempItem);
        }
    }
    if($.browser.msie){
        if($.browser.version == 7.0){
            if(btnCode == 4){
                tempItem = 'detail' + cntId;
                buyContent(tempItem);
            }
        }
    }
}
