var thisLoc = location.host;
var sep = thisLoc.indexOf(".");
var pre = thisLoc.substr(0,sep);
var promoNum = 1;
//Set in header via Genix
var imghost;
var ahost;
var shost;
var khost;
var display_ads = 'False'; //this is set from a Python var. Python uses 'True' 
                           //and 'False', not true and false
var submission_attempts = 0;

$(document).ready(function() {
    //flash detection and redirect
    var hasFlash = detectFlash();
    if (hasFlash == false){
        if(!($.cookie('noFlashAcpted'))){
            showNoFlash();
        }
    }
    //binds custom event to train fires when train animation completes
    $("#train").bind("trainStop", function(event){
        
    }) 
   
   build_logged_in_header();
   
});
function displayUniversalNav() 
{   //function to display the JS version of the Universal Nav
    //will only be called on pages with an id of universalnav present, 
    //and after the DOM loads.
    var divState = 'open';
    var openDef = 'easeOutBounce';
    var closeDef = 'easeInBounce';
    
    $(".navbutton").mouseover(function(){ 
            $(this).stop().animate({marginTop:'-5px'},{queue:false, duration:300, easing: 'easeOutBounce'})  
        }); 
    $(".navbutton").mouseout(function(){  
            $(this).stop().animate({marginTop:'5px'},{queue:false, duration:500, easing: 'easeOutBounce'})  
       });
    $(".navbutton").mousedown(function(){  
            $(this).stop().animate({marginTop:'8px'},{queue:false, duration:600, easing: 'easeOutElastic'})  
       });
    displayBottomBtns();
    setTimeout("displayTrain()", 50);   
}

function displayTrain()
{
//    $('img.fade').cross();
    $("#train").animate({"left": "-2000px"}, 0, 'swing', moveLeft).css('visibility','visible');	
    function moveLeft()
    {
        //raise or lower left by 55px to add or remove a brand
        $("#train").stop().animate({"left": "0px"}, 1750, 'swing', headerLoaded);
    }
}

function headerLoaded()
{
    $("#train").trigger("trainStop");
}
function displayBottomBtns(){
     $(".navbutton_bt").mouseover(function(){ 
            $(this).stop().animate({marginTop:'-5px'},{queue:false, duration:300, easing: 'easeOutBounce'})  
        }); 
    $(".navbutton_bt").mouseout(function(){  
            $(this).stop().animate({marginTop:'-15px'},{queue:false, duration:500, easing: 'easeOutBounce'})  
       });
    $(".navbutton_bt").mousedown(function(){  
            $(this).stop().animate({marginTop:'-18px'},{queue:false, duration:600, easing: 'easeOutElastic'})  
       });
}

function build_logged_in_header()
{
    var ck = getCustomerCookieName();    
    if(_check_val(get_cookie_value(ck, 'si')))
    {   //the customer is signed in        
        var user_name = get_cookie_value(ck, 'name');        
        if(_check_val(user_name)) 
        { 
            $('#agkzname').html(['Hi ',user_name,'!'].join(''));
        }
        var is_parent = get_cookie_value(ck, 'is_parent')
        if(_check_val(is_parent) && is_parent == 'True')
        {
            update = '<a href="' + shost + '/control-panel/home" >Control Panel</a>';
        }  
        else
        {
            update = '<a href="' + shost + '/control-panel/update" >Update</a>';
        } 
        login_out = '<a href="' + shost + '/register/logout/" >Logout</a>';        
    }
    else
    {
       update = '<a href="' + shost + '/register/start" >Register</a>';
       login_out = '<a href="' + shost + '/register/login/" >Login</a>';       
    }
    var sep = ' &nbsp;|&nbsp;  ';
    $('#agkzlogin').html([update, sep, login_out].join('')); 
    $('#agkzloginfooter').html(['<li>',update,'</li><li>', login_out, '</li>'].join(''));
}

function _check_val(val)
{
    return val != null && val != '';
}

//create bookmark in users browser
function createBookmarkLink() 
{
    if($.browser.msie)
    {
        if (document.all)
        {   
            try{window.external.AddFavorite(url,title)}
            catch(err){displayInstr('bm')}
        }
    }
    else 
    {
        displayInstr('bm');
    }
}
//make homepage in users browser
function myHomePage()
{
    if($.browser.msie)
    {
        try{
            document.forms[0].style.behavior='url(#default#homepage)';
            document.forms[0].setHomePage('http://www.agkidzone.com');
        }catch(Error){
            displayInstr('hp');
        }	    
    }
    else  
    {
        displayInstr('hp');
    }
}
//displays instructions based on type passed into will pull needed elements from instr.html
function displayInstr(instrType)
{
    //Removing srv_host. This call should always be relative
    //var srv_host = jQuery.url.attr("protocol") == 'http' ? ahost : shost;
    
    $("#footerTop").append('<div id="Instrs"></div>');
    $("#Instrs").dialog({draggable: true, resizable: true, autoOpen: false, width: 786, height: 522, modal: true, dialogClass: 'popup', title: "AGKidZone Instructions"});
        
    switch(instrType)
    {
        case 'hp' :           
            if($.browser.mozilla)
            {
                (navigator.appVersion.indexOf("Win")!=-1) ? $("#Instrs").load('/instr.html #mhpHeader, #hp_mozilla_win') : $("#Instrs").load(ahost + '/instr.html #mhpHeader, #hp_mozilla_others');
            }
            else if ($.browser.safari)
            {
                $("#Instrs").load('/instr.html #mhpHeader, #hp_safari');
            }else if ($.browser.msie)
            {
                $("#Instrs").load('/instr.html #mhpHeader, #hp_ie');
            }
            break;        
        case 'bm' :
            
            if($.browser.mozilla)
            {
                $("#Instrs").load('/instr.html #mbmHeader, #bm_mozilla');
            }else if ($.browser.safari)
            {
                $("#Instrs").load('/instr.html #mbmHeader, #bm_safari');			
            }else if ($.browser.msie)
            {
                $("#Instrs").load('/instr.html #mbmHeader, #bm_ie');			
            }
            break;
    }
    $(document).ready(function()
    {
        $("#Instrs").dialog('open');
    });
}
//get link to current asset (example: http://dev.web2.agkidzone.com:10103/videos/?id=3176416)
function getLink() {
    var relative_asset_url = catalog_entries[selected_entry].relative_asset_url;
    var relative_asset_url_parts = relative_asset_url.split('/');
    var product_number = relative_asset_url_parts[relative_asset_url_parts.length-2];
    return [(brand == 'spil' ? 'games' : window.location.pathname.substring(1)), '?id=', product_number].join('');
}
//display a link to the asset for the user in a dialog box
function showLinkIt()
{
    
    $("#footerTop").append('<div id="linkitForm"></div>');
    $("#linkitForm").dialog({draggable: true, resizable: true, autoOpen: false, width: 786, height: 522, modal: true, dialogClass: 'popup', title: "AGKidZone Link It"});
    $("#linkitForm").load(ahost + '/social.html #linkIt', function(){ 
        var lnk = [ahost, getLink()].join('/');
        $("#fromLink").val(lnk);          
        //embed copy swf always for putting link onto users clipboard via flash
        flash_vars = {
            clipboard : lnk
        };
        flash_params = {
            allowscriptaccess : 'always',
            wmode : 'transparent'
        };    
        flash_attributes = {
            name : 'copySWF',
            id : 'copySWF'
        };
        swfobject.embedSWF(imghost+'/agkidzone/swf/copy.swf', 'copySWF', '125', '35', '9', imghost+'/js/expressinstall.swf', flash_vars, flash_params, flash_attributes);    
        $("#linkitForm").dialog('open');
    });
    return false;
}

function showEmailPage() {
    if($('#email_dialog').length == 0) {
        $('body').append([
        '<div id="email_dialog" style="display:none;">',
        '<div id="header_logo"></div>',
        '<p id="header_message">Send to a Friend</p>',
        '<a href="#" id="hide_privacy_policy_link" onclick="return hide_privacy_policy()" \
            style="display:none;">close policy</a><form><fieldset><ol>',
        '<li><label for="from">Your First Name</label><input id="from"/></li>',
        '<li><label for="to">Your Friend&#39;s First Name</label><input id="to"/></li>',
        '<li><label for="to_addr">Your Friend&#39;s Email</label><input id="to_addr"/></li>',
        '</ol>',
        '<div id="privacy_disclaimer">Per our ',
        '<a href="#" id="privacy_policy_link" onclick="return open_privacy_policy()">',
        'privacy policy</a> we will not collect or retain your friends&#39; email.</div>',
        '</fieldset></form>',
        '<a href="#" id="submit_button" onclick="return submit_email_request_to_friend()"></a>',
        '<div id="privacy_policy" style="display:none;"></div></div>'
        ].join(''));

        initialize_email_dialog(625, 400, 'Send to a Friend',
            function(event, ui) {
                reset_email_dialog('Send to a Friend');
                hide_privacy_policy();
            }
        );
    }
    return show_email_dialog();
}

function initialize_email_dialog(width, height, title, beforeClose) {
    $('#email_dialog').dialog({draggable: true, resizable: false,
        autoOpen: false, width: width, height: height, modal: true,
        beforeclose: beforeClose, dialogClass: 'popup', title: title
    });
}

function show_email_dialog() {
    $('#email_dialog').dialog('open');
    return false;
}

function open_privacy_policy() {
    var privacy_policy = $('#email_dialog #privacy_policy');
    if(privacy_policy.html() == '') {
        privacy_policy.load(
            ahost + '/privacy-policy #agk-legalpages'
        )
    }
    privacy_policy.fadeIn(300);
    $('#hide_privacy_policy_link').show();
    $('#email_dialog #header_message').hide();
    return false;
}

function hide_privacy_policy() {
    $('#email_dialog #privacy_policy, #email_dialog \
        #hide_privacy_policy_link').hide();
    $('#email_dialog #header_message').show();
    return false;
}

function submit_email_request_to_friend() {
    $('#email_dialog .form_error').remove();

    var from = get_value('#email_dialog #from');
    if(is_blank(from)) {
        mark_invalid('#email_dialog #from');
        $('#email_dialog #from').parent().append(
            '<div class="form_error">\
            Your first name is blank!</div>');
    }
    else {
        mark_valid('#email_dialog #from');
    }

    var to = get_value('#email_dialog #to');
    if(is_blank(to)) {
        mark_invalid('#email_dialog #to');
        $('#email_dialog #to').parent().append(
            '<div class="form_error">\
            Your friend&#39;s first name is blank!</div>');
    }
    else {
        mark_valid('#email_dialog #to');
    }

    var to_addr = get_value(
        '#email_dialog #to_addr');
    if(is_email_address(to_addr)) {
        mark_valid('#email_dialog #to_addr');
    }
    else if(is_blank(to_addr)) {
        mark_invalid('#email_dialog #to_addr');
        $('#email_dialog #to_addr').parent().append(
            '<div class="form_error">\
            Email address is blank!</div>');
    }
    else {
        mark_invalid('#email_dialog #to_addr');
        $('#email_dialog #to_addr').parent().append(
            '<div class="form_error">\
            Email address is incorrectly formatted!</div>');
    }

    if($('#email_dialog .form_error').length == 0) {
        var form_data = {from: from, to: to,
            to_addr: to_addr, link: getLink(),
            brand: (brand == 'my' ? 'my' : '')};
        submit_email_dialog(form_data, '/send-to-friend');
    }
    else {
        set_email_dialog_attempt_message();
    }
    return false;
}

function set_email_dialog_attempt_message() {
    submission_attempts++;
    $('#email_dialog #header_message').html([
        'Attempt ', submission_attempts,
        '<div>Your submission has errors.</div>'
    ].join(''));
}

function submit_email_dialog(form_data, url) {
    $.post([ahost, url].join(''), form_data);
    reset_email_dialog('Your request has been \
        submitted - thank you!');
}

function reset_email_dialog(default_message) {
    submission_attempts = 0;
    $('#email_dialog .form_error').remove();
    $('#email_dialog label').removeClass('valid invalid');
    $('#email_dialog input, #email_dialog textarea').val('');
    $('#email_dialog #header_message').html(default_message);
}

function get_value(selector) {
    return $.trim($(selector).val());
}

function mark_invalid(selector) {
    $(selector).prev().removeClass('valid').addClass('invalid');
}

function mark_valid(selector) {
    $(selector).prev().removeClass('invalid').addClass('valid');
}

function is_blank(value) {
    var regex = /^$/;
    return regex.test(value);
}

function is_email_address(value) {
    var regex = /^.+\@[A-Za-z0-9\-\.]+$/;
    return regex.test(value);
}

function should_display_ads()
{
    return display_ads == 'True';    
}

function build_snowglobe_params()
{
    var params = {
            ahost : ahost,
            path: "holly-hobbie/games?id=",
            prod_id : '3176182'
        };
    
    if(jQuery.url.param("vName") != undefined)
    {
        params.vName = jQuery.url.param("vName");
        params.vFrom = jQuery.url.param("vFrom");
        params.vMsg = jQuery.url.param("vMsg");
        params.vS = jQuery.url.param("vS");
        params.vF = jQuery.url.param("vF");
        params.vIm = jQuery.url.param("vIm");                
    }
    return params;  
}

function secret_code_on_doc_ready(prod_id, ext)
{   //similar to get_and_insert_game_container in catalog.js
    relative_path = ['agp/games/',prod_id,'/'].join('');
    product_base = [imghost,'/product/',relative_path].join('');
    filename = ['secret_code',ext,'.html'].join('')
    
    $.ajax({
        type: 'GET',
        url: '/game-container',
        data: {relative_path : relative_path, 
               filename : filename},
        success: function(container_html){
            subs = {'product_base' : product_base};
            for(sub in subs) {
                regex = new RegExp('\{'+sub+'\}', 'g');
                container_html = container_html.replace(regex, subs[sub]);
            }
            $('#code_content').html(container_html);
        },
        error: function(response_object){
            $('#code_content').html(response_object.responseText);
        }
    });
}

var _intImage = 1;
function swapOFImage(path, scrollToNm) {
    switch (_intImage) {
        case 1:
            document.getElementById("how_btn").src = path + "how_roll.jpg";
            document.getElementById("greeting_txt").src = path + "greeting_roll.jpg";
            _intImage = 2;
            var ret;
            var elem = document.getElementById(scrollToNm);
            ret=findPos(elem);
            scroll(ret[0],ret[1]);
            return(false);
        case 2:
            document.getElementById("how_btn").src = path + "how.jpg";
            document.getElementById("greeting_txt").src = path + "greeting.jpg";
            _intImage = 1;
            var ret;
            var elem = document.getElementById(scrollToNm);
            ret=findPos(elem);
            scroll(ret[0],ret[1]);
            return(false);
    }
}

function swapOFImageNames(path,name1,name2,name3,name4, scrollToNm) {
    switch (_intImage) {
        case 1:
            document.getElementById("how_btn").src = path + name1;
            document.getElementById("greeting_txt").src = path + name2;
            _intImage = 2;
            var ret;
            var elem = document.getElementById(scrollToNm);
            ret=findPos(elem);
            scroll(ret[0],ret[1]);
            return(false);
        case 2:
            document.getElementById("how_btn").src = path + name3;
            document.getElementById("greeting_txt").src = path + name4;
            _intImage = 1;
            var ret;
            var elem = document.getElementById(scrollToNm);
            ret=findPos(elem);
            scroll(ret[0],ret[1]);
            return(false);
    }
}

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];
}
function showNoFlash()
{
    $(document).ready(function() {
        $("#footerTop").append('<div id="noFlash"></div>');
        $("#noFlash").dialog({draggable: true, resizable: true, autoOpen: false, width: 650, height: 270, modal: true, dialogClass: 'popup', title: "AGKidZone Get Flash Player"});
        $("#noFlash").load(ahost + '/instr.html #getFlash', function(){
            $("#gfIMG").attr('src', imghost+'/agkidzone/agkz_noflash.gif');
            $("#noFlash").dialog('open');
            $.cookie('noFlashAcpted', '1', {path:"/"});
        });
    });
}

//open an external site in a new window with our intermediate page
function openSite(site_url)
{
    var popup = window.open(ahost + '/external-site?externalUrl=' + site_url, "_blank");
    popup.focus();
}
// sets cookie for maryoku video 
function fMaryokuCookie ()
{
    $.cookie('maryoku', true, {path:'/', expires:'7'});
}
function fMaryokuCookieCheck()
{
    if($.cookie('maryoku'))
    {
        return true;
    }
}