/* SVN FILE: $Id: animations.js 233 2011-08-02 00:35:53Z zackgordon $ */
/**
 * Base Javascript for Citrix FlexCast
 *
 * @version       	$Revision: 233 $
 * @modifiedby    	$LastChangedBy: zackgordon $
 * @lastmodified  	$Date: 2011-08-01 19:35:53 -0500 (Mon, 01 Aug 2011) $
 */
// FC object for namespace
var flexCast = {};
// languages
flexCast.languages = [
    { code:'de', path:'de/', label:'Deutsch', locale: "de_DE" },
    { code:'en', path:'', label:'English', locale: "en_US" },
    { code:'fr', path:'fr/', label:'Francais', locale: "fr_FR" },
    { code:'zh', path:'zh/', label:'Chinese', locale: "zh_HK" }
];
flexCast.language = flexCast.languages[1];
flexCast.root = '/';
// site path
flexCast.path = '/';
if(document.location.href.indexOf('localhost') > 0){
    flexCast.root = '/clarus/citrix/citrix_flexcast/web/';
    flexCast.path = '/clarus/citrix/citrix_flexcast/web/';
}
flexCast.toolUrl = flexCast.path+'analyzeandcompare.html';
//flexCast.accountsUrl = flexCast.path+'accounts.html';

if(document.location.href.indexOf('source') > 0){
    flexCast.toolUrl = flexCast.path+'source/analyzeandcompare.php';
    //flexCast.accountsUrl = flexCast.path+'source/accounts.php';
}

flexCast.serviceUrl = flexCast.root+'service/json.php';
flexCast.cookieName = "MyCitrixHash";
flexCast.cookieData = null;
flexCast.loginUrl = 'https://www.citrix.com/login?url='+document.location.href;
flexCast.logoutUrl = 'http://support.citrix.com/kc/logout?url='+document.location.href;
flexCast.registerUrl = 'http://citrix.com/English/myCitrix/loginNewUser.asp?url='+document.location.href;

flexCast.strings = {
    login_button:'Log In',
    logout_button:'Log Off',
    account_button:'My Account',
    languages_title:'Languages',
    account_no_login_access :
        '<p class="title">Log in for one-click access to all your FlexCast reports and generate customized TCO analysis with deployment details and benefits for each use case.'+
        '<span>'+
        '<a href="'+flexCast.loginUrl +'">Login with your MyCitrix account</a> '+
        'or '+
        '<a href="'+flexCast.registerUrl +'">Create a MyCitrix Account</a><span></p>',
    account_no_sessions :'<p class="title">Currently you have no saved reports. <a href="'+flexCast.toolUrl +'?launch=1">Start your first report here and save them to your account</a>.</p>',
    loading_accounts:'<p class="loading"><span>Loading Accounts...</span></p>',
    loading_accounts_error:'<p class="error">Error loading Sessions. Make sure you are logged in and try again.</p>',

    delete_session_confirm:'Are you sure you want to delete the session from your history?'
};

// Nothing below should be edited /////////////////////////////////////////////////////////
// flags
flexCast.shouldLoadAccounts = false;

// generates language menu HTML
flexCast.languageMenuHTML = function(data){
    var filePath = (flexCast.path != '/') ? document.location.pathname.replace(flexCast.path,'') : '';
    // patch for index.en
    filePath = filePath.replace('.en','');
    //console.log(filePath);
    var html =  '<ul class="footerColLast">'+
        '<li><h6>'+flexCast.strings.languages_title+'</h6></li>';
    for( var i in data ){
        var lang = data[i];
        if(lang.label){
            if( lang != flexCast.language ){
                html += '<li><a href="'+flexCast.root+lang.path+filePath+'">'+lang.label+'</a></li>';
            }else{
                html += '<li>'+lang.label+'</li>';
            }
        }
    }
    html += '</ul>';
    return html;
};

flexCast.accountTableRowHTML = function(data,index){
    if(!data) return '';
    var rowClass = (index%2==0) ? 'even' : 'odd';
    return '<tr class="'+rowClass+'">'+
 		'<td class="sessionname">'+(data.sessionname || '')+'</td>'+
        '<td class="name">'+(data.name || '')+'</td>'+
        '<td class="email">'+(data.email || '')+'</td>'+
        '<td class="company">'+(data.company || '')+'</td>'+
        '<td class="phone">'+(data.phone || '')+'</td>'+
        '<td class="notes">'+(data.notes || '')+'</td>'+
        '<td class="launch"><a href="'+flexCast.toolUrl+'?sessid='+data.id+'" class="launchButton">Launch</a></td>'+
        '<td class="delete"><a href="'+'?sessid='+data.id+'&uid='+data.userid+'&key='+data.key+'" class="deleteButton">Delete</a></td>'+
        '</tr>';
};

flexCast.messageHTML = function(message){
    return '<div class="message"><p>'+message+'</p></div>';
};

flexCast.showReportMessage = function(message){
    $('.section .message').remove();
    if( message ){
        $('.section').append('<div class="message">'+message+'</div>');
    }
};

flexCast.deleteClickHandler = function(){

    if(confirm(flexCast.strings.delete_session_confirm)){

        var deleteData = parseQueryString($(this).attr('href'));
        deleteData.id2 = flexCast.cookieData['ID2'];
        deleteData.call = 'deleteSession';

        var row = this;

        $.getJSON(flexCast.serviceUrl,
            deleteData,
            function(data, textStatus, jqXHR) {

                if(data.hasOwnProperty('result')){

                    if( data.result != 'success' ){
                        //alert(data.result);
                    }else{
                        $(row).parent().parent().fadeOut( 500, function(){
                            if($("#accountsList tbody tr").length == 1){
                                $("#accountsList tbody").html('');
                                $("#accountsList").fadeOut(400,function(){
                                    flexCast.showReportMessage(flexCast.strings.account_no_sessions);
                                });

                            }else{
                                $(this).remove();
                                $("#accountsList tbody tr").each(function(index) {
                                    $(this).toggleClass('even',((index+1)%2==0));
                                    $(this).toggleClass('odd',((index+1)%2!=0));
                                });
                            }
                        });
                    }
                }
            });
    }
    return false;
};

flexCast.checkLogin = function(){

    // Check for a session cookie
    var loginCookie = getCookie(flexCast.cookieName);
    var loggedIn = false;
    var isAccountsPage = document.getElementById("accounts");

    if(loginCookie){
        flexCast.cookieData = parseQueryString(loginCookie,{});
        loggedIn = ( flexCast.cookieData && flexCast.cookieData.hasOwnProperty('ID1') && flexCast.cookieData.hasOwnProperty('ID2'));
    }

    if(!loggedIn){
        $("#accountsList").fadeOut();

        //$("#login a").text(flexCast.strings.login_button).attr('href',flexCast.loginUrl);
        $("#loginAccountButton").text(flexCast.strings.login_button).attr('href',flexCast.loginUrl);

        if(isAccountsPage){

            // Show alert
            flexCast.showReportMessage(flexCast.strings.account_no_login_access);
        }
    }else{

        //$("#login a").text(flexCast.strings.logout_button).attr('href',flexCast.logoutUrl);
        $("#loginAccountButton").text(flexCast.strings.logout_button).attr('href',flexCast.logoutUrl);

        if(isAccountsPage){

            // Check login and load sessions
            flexCast.showReportMessage(flexCast.strings.loading_accounts);

            var callData = {
                call:'authenticateAndReturnSessions',
                id1: flexCast.cookieData['ID1'],
                id2: flexCast.cookieData['ID2'] };

            flexCast.shouldLoadAccounts = true;
            $("#accountsList tbody").html('');

            $.getJSON(flexCast.serviceUrl,
                callData,
                function(data, textStatus, jqXHR) {
                    if(!flexCast.shouldLoadAccounts) return;
                    if(data && data.length>0){

                        $.each(data, function(key, val) {
                            $("#accountsList tbody").append($(flexCast.accountTableRowHTML(val,key+1)));
                        });

                        // Setup Delete Buttons in new rows
                        $('.deleteButton').click(flexCast.deleteClickHandler);

                        // Remove loading message
                        $('.section .message').fadeOut(400,function(){
                            $(this).remove();
                            $("#accountsList").fadeIn();
                        });

                    }else{
                        flexCast.showReportMessage(flexCast.strings.account_no_sessions);
                    }
                    flexCast.shouldLoadAccounts = false;
                }).error(function() {

                    flexCast.showReportMessage(flexCast.strings.loading_accounts_error);
                    flexCast.shouldLoadAccounts = false;
                });
        }
    }

    //$('#login').fadeIn();
};

flexCast.loadFlashTool = function(){

    var map = getUrlVars();
    var d = ( map.debug ) ? '-debug' : '';
    var rs = ( map.nocache ) ? "?nocache="+randomString() : '';

    $('.bottom').fadeOut('slow');
    $('#intro').fadeOut('slow',function() {

        $('#media_container').html('<div id="tool_media"><h2>You need to install the Adobe Flash Player to watch this video.</h2><h2><a href="http://get.adobe.com/flashplayer">Download it from Adobe.</a></h2></div>');
        $('#media_container').addClass('toolActive');

        var embed = {
            swf: flexCast.root+"flexcast_tco_app/FlexCast.swf"+rs,
            container: "tool_media",
            width: "960",
            height: "590",/* starting swf height */
            version: "10.0.0",
            expressInstall: "expressInstall.swf"
        };

        var flashvars = {
            locale: flexCast.language.locale
        };

        if( map.sessid ) flashvars.sessid = map.sessid;

        var params = {
            menu: "false",
            allowFullScreen: "true",
            allowScriptAccess: "always",
            wmode:"transparent",
            base: flexCast.root+"flexcast_tco_app"
        };

        var attributes = {
            id: "swf"
        };

        swfobject.embedSWF(embed.swf, embed.container, embed.width, embed.height, embed.version, embed.expressInstall, flashvars, params, attributes );

        setFlashHeight(embed.height);
    });
};

// Place init code here instead of $(document).ready()
google.setOnLoadCallback(function() {

    // Page overrides
    // Remove default login, this is also hidden via CSS
    $("#login").remove();
    // Swap classes on the last col and insert our own
    $(".footerColLast").removeClass('footerColLast').addClass('footerCol');
    $("#footerRt").append($(flexCast.languageMenuHTML(flexCast.languages)));

    // Disable clicks on top level button
    $("#sectionAccountButton").click(function(){ return false; });
    //$('#accountButton').text(flexCast.strings.account_button).attr('href',flexCast.accountsUrl);

    flexCast.checkLogin();

    // Nav
    $('.nav > li a').mouseover(function() {
        $(this).next('.sub-nav').slideDown(250);
    });

    $('.nav > li').mouseleave(function() {
        $(this).find('.sub-nav').slideUp(100);
    });

    // Embed flash ////////////////////////////
    var mediaClass = $('#media').attr('class');

    var map = getUrlVars();
    var d = ( map.debug ) ? '-debug' : '';
    var rs = ( map.nocache ) ? "?nocache="+randomString() : '';

    var isToolPage = document.getElementById('flexcast_tool');

    if( isToolPage ){

        if(map.hasOwnProperty('launch') || map.hasOwnProperty('sessid')){
            flexCast.loadFlashTool();
        }

    }else if( mediaClass != undefined && mediaClass != '' ) {

        var parts = mediaClass.split(' ');
        var section = parts[0];
        var slide = parts[1];
        var embed = {
            swf: flexCast.root+"swf/CitrixPlayer"+d+".swf"+rs,
            container: "media",
            width: "980",
            height: "390",
            version: "9.0.124.0",
            expressInstall: "expressInstall.swf"
        };

        var flashvars = {
            'config' : flexCast.path+'swf/'+section+'.php'
        };

        if( slide ){
            flashvars.slide = slide;
        }

        flashvars = getUrlVars( flashvars );

        var params = {
            menu: "false",
            allowFullScreen: "true",
            allowScriptAccess: "always",
            wmode:"transparent"
        };

        var attributes = {
            id: "swf"
        };


        if( !swfobject.hasFlashPlayerVersion(embed.version) )
        {
            $("#media img").css( "display", "block" );
            $('#media').html('<div id="tool_media"><h2>You need to install the Adobe Flash Player to watch this video.</h2><h2><a href="http://get.adobe.com/flashplayer">Download it from Adobe.</a></h2></div>');
        }
        else
        {
            swfobject.embedSWF(embed.swf, embed.container, embed.width, embed.height, embed.version, embed.expressInstall, flashvars, params, attributes );
        }
    }

    $('.tool-btn').click(flexCast.loadFlashTool);

// Case Study Items

    $.each( $('#study_items .box'), function(key,value){
        if(  $(value).hasClass('selected') ){
            $('#'+$(value).attr('id')+'_content').show();
        }
    });

    $('#study_items .box').click( function(){
        var c = this;
        $.each( $('#study_items .box'), function(key,value){

            if( value == c ){
                $(value).addClass('selected');
                $('#'+$(value).attr('id')+'_content').show();
            }else{
                $(value).removeClass('selected');
                $('#'+$(value).attr('id')+'_content').hide();
            }
        });
    });
});
