
var version_GLOBAL      = 20100528;
var pageLoadTime_global = '';

var travelController_global = 'location';
var travelUpdateId_global   = 'app-response-message';

function onClickHide(containerId) { $("#" + containerId).hide(); }
function onClickShow(containerId) { $("#" + containerId).show(); }
function showHideDiv(containerId) { $("#" + containerId).toggle(); }
function toggleClass(containerId, classNameVar) { $("#" + containerId).toggleClass(classNameVar); }
function triggerAction(containerId, actionType) { $("#" + containerId).trigger(actionType); }
function toggleHideShow(containerId) { $("#" + containerId).toggle(); }

function selectRadio(pos, radioId, divId, selectedClass)
{
	for( i=0; i<100; i++ )
	{
	   el = $("#"+divId + i);
	   if(el == null) { break; }
	   el.removeClass(selectedClass);
	}

	$("#"+radioId + pos ).attr('checked', true);

	$("#"+divId + pos).addClass(selectedClass);
}

function attributeCountdown(secondsLeft, maxSeconds, countdownId, curVal, maxVal, updateVal, valId, pageLoadTime)
{
    if (pageLoadTime != pageLoadTime_global)    { return; }

    var countdown_id = $('#'+countdownId);
    var value_id = $('#'+valId);

    // countdown container does not exist return
    if (countdown_id.length == 0 || value_id.length == 0) { return; }

    // is it time to reload element id?
    if (secondsLeft <= 0)
    {
        var newVal = curVal + updateVal;

        if (newVal >= maxVal)
        {
            value_id.text(maxVal+'/'+maxVal);
            $('#'+countdownId+'-morein').css('display', 'none');
            return;
        }
        else
        {
            value_id.text(newVal+'/'+ maxVal);
            countdown_id.text(getSimpleCountdownFormat(maxSeconds));
            setTimeout(function() {attributeCountdown(maxSeconds, maxSeconds, countdownId, newVal, maxVal, updateVal, valId, pageLoadTime);} , 1000);
        }
    }
    else
    {
        secondsLeft--;
        countdown_id.text(getSimpleCountdownFormat(secondsLeft));
        setTimeout(function() {attributeCountdown(secondsLeft, maxSeconds, countdownId, curVal, maxVal, updateVal, valId, pageLoadTime);} , 1000);
    }
} // attributeCountdown()

function getSimpleCountdownFormat(secondsLeft)
{
    var seconds = (secondsLeft % 60);

    var minutesLeft = Math.floor(secondsLeft / 60);
    var minutes = (minutesLeft % 60);

    var hoursLeft = Math.floor(minutesLeft / 60);
    var hours = (hoursLeft % 24);

    hours = hoursLeft;

    if(hours > 0) { var countdownText = hours + ":" + addZero(minutes) + ":" + addZero(seconds); }
    else { var countdownText = minutes + ":" + addZero(seconds); }

    return countdownText;
}

function addZero(num)
{
    if ((num >= 0) && (num < 10)) { num = '0' + num; }
    return num;
}


function updateBoostTextValue(formValueId, textValueId, multiplier, baseValue)
{
    form_value = parseInt($('#'+formValueId).val());

    if (form_value < 0) { form_value = 0; }

    form_value  = form_value*multiplier;
    baseValue   = baseValue*1;
    new_val     = (form_value+baseValue);

    $('#'+textValueId).html(new_val);
} // updateBoostTextValue()

function scrollToAnchor(pageAnchor)
{
    if (pageAnchor != '' && $('#'+pageAnchor).length > 0)
    {
		var destination = $('#'+pageAnchor).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 300, function() {
			window.location.hash = '#'+pageAnchor;
		});
    }
}

function submitForm(page, formId, divId, hide, jumpToTop)
{
    if ( typeof hide === 'undefined' )       { hide = false; }
    if ( typeof jumpToTop === 'undefined' )  { jumpToTop = true; }
    if ( typeof divId === 'undefined' )      { divId = 'inner-container'; }

    var appData = $('#' + formId).serialize();

    getPage(page, appData, divId, hide, jumpToTop);
}

function topOfApplication() { $('#top-anchor-input').focus() }
function switchBackground(element_id, image_url) { $('#'+element_id).css('background-image', 'url(' + image_url + ')'); }

/*CAROUSEL JS*/
(function($){$.fn.tinycarousel=function(options){var defaults={start:1,display:1,axis:'x',controls:true,pager:false,interval:false,intervaltime:3000,animation:true,duration:1000,callback:null};var options=$.extend(defaults,options);var oSlider=$(this);var oViewport=$('.viewport',oSlider);var oContent=$('.overview',oSlider);var oPages=oContent.children();var oBtnNext=$('.next',oSlider);var oBtnPrev=$('.prev',oSlider);var oPager=$('.pager',oSlider);var iPageSize,iSteps,iCurrent,oTimer,bForward=true,bAxis=options.axis=='x';return this.each(function(){initialize();});function initialize(){iPageSize=bAxis?$(oPages[0]).outerWidth(true):$(oPages[0]).outerHeight(true);var iLeftover=Math.ceil(((bAxis?oViewport.outerWidth():oViewport.outerHeight())/(iPageSize*options.display))-1);iSteps=Math.max(1,Math.ceil(oPages.length/options.display)-iLeftover);iCurrent=Math.min(iSteps,Math.max(1,options.start))-2;oContent.css(bAxis?'width':'height',(iPageSize*oPages.length));move(1);setEvents();}
function setButtons(){if(options.controls){oBtnPrev.toggleClass('disable',!(iCurrent>0));oBtnNext.toggleClass('disable',!(iCurrent+1<iSteps));}}
function setEvents(){if(options.controls&&oBtnPrev.length>0&&oBtnNext.length>0){oBtnPrev.click(function(){move(-1);return false;});oBtnNext.click(function(){move(1);return false;});}if(options.pager&&oPager.length>0){oPager.click(setPager);}}
function setPager(oEvent){var oTarget=oEvent.target;if($(oTarget).hasClass('pagenum')){iCurrent=parseInt(oTarget.rel)-1;move(1);}return false;}
function setPagerActive(){if(options.pager){var oNumbers=$('.pagenum',oPager);oNumbers.removeClass('active');$(oNumbers[iCurrent]).addClass('active');}}
function setTimer(bReset){if(options.interval&&!bReset){clearInterval(oTimer);oTimer=window.setInterval(function(){bForward=iCurrent+1==iSteps?false:iCurrent==0?true:bForward;move(bForward?1:-1,true);},options.intervaltime);}}
function move(iDirection,bTimerReset){if(iCurrent>0||iCurrent+1<iSteps){iCurrent+=iDirection;var oPosition={};oPosition[bAxis?'left':'top']=-(iCurrent*(iPageSize*options.display));oContent.animate(oPosition,{queue:false,duration:options.animation?options.duration:0,complete:function(){if(typeof options.callback=='function')options.callback.call(this,oPages[iCurrent],iCurrent);}});setButtons();setPagerActive();setTimer(bTimerReset);}}};})(jQuery);

function closeModal()
{
    //var children = $("#empty_modal_container").children();
    //alert(children.length);

	$('#mask').hide();
	$('.modal-window').hide();
}

$('#mask').click(function() {
	closeModal();
});

jQuery.fn.launchModal = function (options) {
return this.each (function () {

    var settings = $.extend({ "modal_class": "default-modal", "modal_close": true, "ajax_post": false, "ajax_params": "", "autoclose": 0},options);

    var modalDivId = this.id + "_modal";
    var modalCallbackId = this.id + "_callback";

    var closeContent = '';
    if(settings.modal_close)
    {
        closeContent = "<div class='modal-close' onclick='closeModal();'></div>";
    }

    var modalDivElement = $("#" + modalDivId);
    if(modalDivElement.length > 0)
    {
        modalDivElement.remove();
    }

    $("#empty_modal_container").append("<div id='" + modalDivId + "' class='modal-window " + settings.modal_class + "'>" + closeContent + "<div id='" + modalCallbackId + "'></div></div>");

    modalDivElement = $("#" + modalDivId);
    var modalCallbackElement = $("#" + modalCallbackId);

    var y = $("#" +this.id).offset().top;
    if(y === null || y === 'undefined' || y == 0)
    {
        y = 200;
    }

    if(settings.ajax_post)
    {
        getContent(settings.ajax_post,settings.ajax_params, modalCallbackId);
    }
    else
    {
        var modalContent = $("#" + this.id + "_content").html();
        modalCallbackElement.html(modalContent);
    }

	var maskHeight = $(window).height();
	var maskWidth = $("#inner-container").width();
    var idWidth = modalDivElement.width();
    var idHeight = modalDivElement.height();

	$('#mask').css({'width':maskWidth,'height':maskHeight});

    var widthDifference = Math.floor((maskWidth-idWidth)/2);
    widthDifference = widthDifference - 10;
	modalDivElement.css('top',  y - Math.floor(idHeight/2));
	modalDivElement.css('left', widthDifference );

	$('#mask').show();
    modalDivElement.show();

    if(settings.autoclose > 0)
    {
        setTimeout(function() {
            closeModal();
        }, settings.autoclose);
    }


});
}

function limitTextAreaText(textAreaId, limitCount, limitNum)
{
	if ($("#"+textAreaId).val().length > limitNum) {
		$("#"+textAreaId).val($("#"+textAreaId).val().substring(0, limitNum));
	} else {
	    if(limitCount.length > 0)
	    {
		    $("#" + limitCount).text(limitNum - $("#"+textAreaId).val().length);
		}
	}
}

var clearTextAreaFlag = true;
function clearTextArea(textAreaId, submitId)
{
	if (clearTextAreaFlag == true) {
		$("#"+textAreaId).val('');
	    $("#"+textAreaId).css('height', '35px');
	    clearTextAreaFlag = false;
	    $("#"+submitId).show();
	}
}

var _statsCount = 0;
function showNotice(options)
{
    var settings = $.extend({ "id": ("gs"+_statsCount++), "title": "", "message": "", "cls": false, "speed": 200, "timeout": false},options);

    if($("#"+settings.id).length!=0) {$("#"+settings.id).remove();}

    //append status
    $("#growlcontainer").prepend('<div id="'+settings.id+'" class="growlstatus" style="display:none;"><div class="growlstatusclose"></div>'+settings.message+'</div>');

    var status = $("#"+settings.id);

    //bind close button
    status.find(".growlstatusclose").bind('click',function(){closeNotice(settings.id,true,settings.speed);});

    if(settings.cls!==false){ status.addClass("growlclass_"+settings.cls);}

    var close_timeout_id = 0;
    if(settings.timeout!=false)
    {
      close_timeout_id = window.setTimeout("closeNotice('"+settings.id+"')", settings.timeout);
    }

    //do not hide on hover
    status.hover(function(){
            $(this).addClass("growlhover");},
        function(){
            $(this).removeClass("growlhover");
            if(settings.timeout!=false){
                window.clearTimeout(close_timeout_id);
                window.setTimeout("closeNotice('"+settings.id+"')", settings.timeout);
            }
    }).show();
}

function closeNotice(id,force,speed)
{
  if(!$("#"+id).hasClass("growlhover") || force){ $("#"+id).remove(); }
}


function addNotice(message_param, title_param, class_param, timeout_param, html_flag)
{
    if ( typeof title_param === 'undefined' )   { title_param = ''; }
    if ( typeof class_param === 'undefined' )   { class_param = ''; }
    if ( typeof timeout_param === 'undefined' ) { timeout_param = false; }
    if ( typeof html_flag === 'undefined' )     { html_flag = 0; }

    if ( html_flag == 0 )
    {
        showNotice({
          'title'  : title_param,
          'message': message_param,
          'cls'   : class_param,
          'timeout': timeout_param
        });
    }
    else
    {
        showNotice({
          'title'  : title_param,
          'message': $("#" + message_param).html(),
          'cls'   : class_param,
          'timeout': timeout_param
        });
    }

}

function showToolTip(tipId, showBelow, offsetDiv)
{
    if ( typeof showBelow === 'undefined' ) { showBelow = false; }
    if ( typeof offsetDiv === 'undefined' ) { offsetDiv = false; }

    var pageWidthHalf = $("#inner-container").width()/2;

    var elementX = $('#'+tipId+"_trigger").offset().left;
    var elementY = $('#'+tipId+"_trigger").offset().top;
    var elementHeight = $('#'+tipId+"_trigger").height();
    var elementWidth = $('#'+tipId+"_trigger").width();
    var tipWidth = $('#'+tipId).width();
    var tipHeight = $('#'+tipId).height();

    $('#'+tipId).show();

    if(offsetDiv != false)
    {
        elementX = elementX - $('#'+offsetDiv).offset().left;
        elementY = elementY - $('#'+offsetDiv).offset().top;
    }

    if(showBelow != false)
    {
        $('#'+tipId).css('top', elementY + elementHeight );

        if(elementX < pageWidthHalf)
        {
            $('#'+tipId).css('left', elementX );
        }
        else
        {
            $('#'+tipId).css('left', elementX - (tipWidth - elementWidth) );
        }
    }
    else
    {
        $('#'+tipId).css('top', elementY - (tipHeight - elementHeight) );

        if(elementX < pageWidthHalf)
        {
            $('#'+tipId).css('left', elementX + elementWidth );
        }
        else
        {
            $('#'+tipId).css('left', elementX - tipWidth );
        }
    }

    $('#'+tipId).mouseleave(function () { $('#'+tipId).hide(); });
    $('#'+tipId).mouseenter(function () { $('#'+tipId).show(); });
    $('#'+tipId+"_trigger").mouseleave(function () { $('#'+tipId).hide(); });
}

function simpleSecondCountDownTimer(secondsLeft, countdownId)
{
    var countdown_id = $('#'+countdownId);

    if (countdown_id.length == 0) { return; } // countdown container does not exist, then return

    if (secondsLeft <= 0)
    {
        return;
    }
    else
    {
        secondsLeft--;

        var seconds = (secondsLeft % 60);

        var minutesLeft = Math.floor(secondsLeft / 60);
        var minutes = (minutesLeft % 60);

        var hours = Math.floor(minutesLeft / 60);

        if (hours > 0) { countdown_id.text(hours + ":" + addZero(minutes) + ":" + addZero(seconds)); }
        else { countdown_id.text(minutes + ":" + addZero(seconds)); }

        setTimeout(function() {simpleSecondCountDownTimer(secondsLeft, countdownId);} , 1000);
    }
} // secondCountDownTimer()

var totalSkillPoints_global                 = 0;
var skillAttributesAllocated_global         = {};

var skillPointsRequiredPerAttribute_global  = {};
var skillPointsBulkMultiplier_global        = 5;

function addSkillPoint(attribute, requiredSkillPoints, valueToAdd)
{
    // does user have enough skill points?
    if (totalSkillPoints_global < requiredSkillPoints)
    {
        return;
    }

    var hidden_id   = attribute + '_skill_points';
    var text_id     = attribute + '_text';
    var added_id    = attribute + '_added';

    var updated_attribute_value             = parseInt($("#"+text_id).text()) + valueToAdd;
    var updated_attribute_spent_skill_value = parseInt($("#"+hidden_id).val()) + requiredSkillPoints;

    $("#"+hidden_id).val(updated_attribute_spent_skill_value);

    $("#"+text_id).text(updated_attribute_value);

    skillAttributesAllocated_global[attribute] = skillAttributesAllocated_global[attribute] + valueToAdd;

    $("#"+added_id).text('[+' +skillAttributesAllocated_global[attribute] + ']');

    totalSkillPoints_global = totalSkillPoints_global - requiredSkillPoints;
    $("#total_skill_points_text").text(totalSkillPoints_global);

    $.each(skillPointsRequiredPerAttribute_global,
        function (index, value)
        {
            if (skillPointsRequiredPerAttribute_global[index] > totalSkillPoints_global)
            {
                $("#"+index+"_increase_button").hide();
            }
            if ((skillPointsBulkMultiplier_global*skillPointsRequiredPerAttribute_global[index]) > totalSkillPoints_global)
            {
                $("#"+index+"_increase_multi_button").hide();
            }

        });
} // addSkillPoint()