window.pemco = window.pemco || {};

/*
Controls site functions not applicable to a particular widget
*/
(function($) {

    /****** SETTINGS *******/
    var strAjaxHandler = 'ajax/default.aspx';

    var pub = pemco.home = {};

    var setting = {};
    setting.transSpeed = 500;
    setting.currentMode = 'home_init';
    setting.oldMode = '';
    setting.somethingIsLoaded = false;
    setting.loadFunction = function() { };

    var panel = {};
    panel.home = '#home_top';
    panel.pemco_carousel = '#carousel_panel';
    panel.user_carousel = '#user_carousel_panel';
    panel.profile_spotted = '#profile_spotted_panel';
    panel.commercials = '#commercials_panel';
    panel.create_profile = '#create_profile_panel';
    panel.my_profiles = '#my_profiles_panel';

    /****** PUBLIC FUNCTIONS *******/

    pub.raise = function(speed) {
        pub.hideBackground(speed);
    }

    pub.lower = function(speed) {
        pub.showBackground(speed);
    }

    pub.hideBackground = function(speed) {
        //$(panel.home).animate({ backgroundPosition: 'left -247px' }, speed || setting.transSpeed);
        $(".home_background").fadeOut(speed || setting.transSpeed);
    }

    pub.showBackground = function(speed) {
        //$(panel.home).animate({ backgroundPosition: 'left 0px' }, speed || setting.transSpeed);
        if (setting.currentMode == 'carousel') {
            $(".home_background").fadeIn(speed || setting.transSpeed);
        }
    }

    pub.carouselMode = function() {
        pub.toggleButtons('our');

        switchMode('carousel');
        //pub.getUserProfileThumbnails();   //Commented out by Tri on 4/1/2011 remove on Phase 3
    }

    pub.userCarouselMode = function() {
        pub.toggleButtons('your');

        switchMode('carousel');
    }

    pub.toggleButtons = function(active) {
        if (active == 'our') {
            $("#profiles_your_button a").html("<img src='images/profiles_your_inactive.gif' alt='' />");
            $("#profiles_our_button a").html("<img src='images/profiles_our.gif' alt='' />");
        }
        else {
            $("#profiles_your_button a").html("<img src='images/profiles_your.gif' alt='' />");
            $("#profiles_our_button a").html("<img src='images/profiles_our_inactive.gif' alt='' />");
        }
    }

    pub.profileSpottedMode = function() {
        pub.toggleButtons('our');

        switchMode('profile_spotted');
    }

    pub.commercialsMode = function(fn) {
        pub.toggleButtons('our');

        fn = $.isFunction(fn) ? fn : function() { };

        $("#commercial_button").removeClass("commercial_button_clickable");
        $("#commercial_button").addClass("commercial_button_selected");
        switchMode('commercials');
    }

    pub.createProfileMode = function() {
        pub.toggleButtons('your');

        pemco.create_profile.initCreateProfile(strAjaxHandler);
        switchMode('create_profile');
    }

    pub.editProfileMode = function() {
        pub.toggleButtons('your');

        switchMode('create_profile');
    }

    pub.myProfilesMode = function() {
        pub.toggleButtons('your');

        if (pemco.user != undefined) {
            pemco.user.getMyAccountDetails(strAjaxHandler);
        }

        switchMode('my_profiles');
    }

    pub.getEventCalendarMode = function() {
        pub.toggleButtons('our');

        switchMode('calendar');
    }

    pub.openMoreProfilesBox = function(speed) {

        $("#see_more_profiles_button").html("<a href='javascript:pemco.home.closeMoreProfilesBox();'><img src='images/see_more_profiles.gif' border='0' /></a>");
        //$("#map_sidebar_title"              ).html("<a class='title seen' href='javascript:pemco.home.closeMoreProfilesBox();'><span>Seen this profile?</span></a>");
        //$("#create_profile_sidebar_title"   ).html("<a class='title seen' href='javascript:pemco.home.closeMoreProfilesBox();'><span>Create your own profile</span></a>");

        $("#see_more_profiles_box").slideDown(speed || setting.transSpeed);
        $("#map_sidebar_content").slideUp(speed || setting.transSpeed);
        $("#create_profile_sidebar_content").slideUp(speed || setting.transSpeed);

        $('#more_profiles_pane').jScrollPane({
            dragMaxHeight: 14,
            animateTo: true,
            showArrows: true
        });

        scrollSidebarTo(pemco.carousel.getCenterProfileID());
    }

    pub.closeMoreProfilesBox = function(speed) {

        $("#see_more_profiles_button").html("<a href='javascript:pemco.home.openMoreProfilesBox();'><img src='images/see_more_profiles_inactive.gif' border='0' /></a>");
        //$("#map_sidebar_title"              ).html("<a class='title seen' href='#profilespotted'><span>Seen this profile?</span></a>");
        //$("#create_profile_sidebar_title"   ).html("<a class='title seen' href='#create_profile'><span>Create your own profile</span></a>");

        $("#see_more_profiles_box").slideUp(speed || setting.transSpeed);
        $("#map_sidebar_content").slideDown(speed || setting.transSpeed);
        $("#create_profile_sidebar_content").slideDown(speed || setting.transSpeed);
    }

    var lastCodename;
    pub.hiliteSidebarProfile = function(codename) {
        if (lastCodename) $("#proflink-" + lastCodename).removeClass('active');
        scrollSidebarTo(codename);
        lastCodename = codename;
    }

    var scrollSidebarTo = function(codename) {
        var $pane = $('#more_profiles_pane');
        if (!($pane[0] && $pane[0].scrollTo)) return;
        if (codename) {
            var $scroll = $pane.closest('.jScrollPaneContainer');
            var $center = $('#proflink-' + codename);
            if ($center[0]) {
                var scrollPx = Math.min(Math.max(0, $center.position().top - ($scroll.height() / 2)), $pane.height() + ($scroll.height() / 2));
                $pane.find('.active').removeClass('active');
                $center.addClass('active');
                $pane[0].scrollTo(scrollPx);
                return;
            }
        }
        $pane[0].scrollTo(0);
    }

    pub.makeSureSomethingIsLoaded = function() {
        if (!setting.somethingIsLoaded) {
            pemco.home.carouselMode();
            //pemco.carousel.construct();
        }
        pemco.user.isSignedIn(strAjaxHandler);
    }

    pub.getUserProfileThumbnails = function() {

        var objElement = document.getElementById("divThumbnails");
        if (objElement != null) {

            var data = { 'action': 'get_user_profile_thumbnails' };

            jQuery.ajax({
                type: "POST",
                url: strAjaxHandler,
                dataType: "json",
                data: data,
                success: function(response) {
                    if (response) {
                        if (response.status == "Success") {
                            objElement.innerHTML = response.html;
                        }
                    }
                    else {
                        pemco.ajax.flash(response.message, response.status);
                    }
                },
                error: function() { pemco.ajax.flash("Fail to get user thumbnails.", "Error"); }
            });

        }
    }

    pub.resetCarouselDiv = function(type) {
        var strVersion = "9.0.124";

        switch (type) {
            case "our":
                strVersion = "10.1.52";
                break;
            default:
                break;
        }

        if ($("#carousel_panel").length > 0) {
            $("#carousel_panel").html('<div id="pemco_carousel_content"><a href="http://www.adobe.com/go/getflash">' +
            '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />' +
            '</a>' +
            '<p>This page requires Flash Player version ' + strVersion + ' or higher.</p></div>');
        }
    };

    pub.createProfileCarousel = function() {
        // Called by Flash to pass default values on load
        //xmlPath = "files/xml/ProfileCarousel.xml";
        // End functions

        //<!-- Adobe recommends that developers use SWFObject2 for Flash Player detection. -->
        //<!-- For more information see the SWFObject page at Google code (http://code.google.com/p/swfobject/). -->
        //<!-- Information is also available on the Adobe Developer Connection Under "Detecting Flash Player versions and embedding SWF files with SWFObject 2" -->
        //<!-- Set to minimum required Flash Player version or 0 for no version detection -->
        var swfVersionStr = "10.1.52";
        //<!-- xiSwfUrlStr can be used to define an express installer SWF. -->
        var xiSwfUrlStr = "";
        var flashvars = {};
        var params = {};
        params.quality = "high";
        params.bgcolor = "#f3efe7";
        params.outline = "none";
        params.play = "true";
        params.loop = "true";
        params.wmode = "transparent";
        params.scale = "showall";
        params.menu = "false";
        params.devicefont = "false";
        params.salign = "";
        params.allowscriptaccess = "sameDomain";
        var attributes = {};
        attributes.id = "ProfileCarousel";
        attributes.name = "ProfileCarousel";
        attributes.align = "middle";
        swfobject.embedSWF(
				    "ProfileCarousel.swf", "pemco_carousel_content",
				    "950", "430",
				    swfVersionStr, xiSwfUrlStr,
				    flashvars, params, attributes);

        //        if (typeof callback == 'function') { // make sure the callback is a function
        //            callback.call(this); // brings the scope to the callback
        //        }

    };

    pub.createUserCarousel = function() {

        //xmlPath = "files/xml/UserCarousel.xml";

        //<!-- Adobe recommends that developers use SWFObject2 for Flash Player detection. -->
        //<!-- For more information see the SWFObject page at Google code (http://code.google.com/p/swfobject/). -->
        //<!-- Information is also available on the Adobe Developer Connection Under "Detecting Flash Player versions and embedding SWF files with SWFObject 2" -->
        //<!-- Set to minimum required Flash Player version or 0 for no version detection -->
        var swfVersionStr = "9.0.124";
        //<!-- xiSwfUrlStr can be used to define an express installer SWF. -->
        var xiSwfUrlStr = "";
        var flashvars = {};
        var params = {};
        params.quality = "high";
        params.bgcolor = "#f3efe7";
        params.play = "true";
        params.loop = "true";
        params.wmode = "transparent";
        params.scale = "showall";
        params.menu = "false";
        params.devicefont = "false";
        params.salign = "";
        params.allowscriptaccess = "sameDomain";
        var attributes = {};
        attributes.id = "ProfileCarouselUser";
        attributes.name = "ProfileCarouselUser";
        attributes.align = "middle";
        swfobject.embedSWF(
				    "ProfileCarouselUser.swf", "pemco_carousel_content",
				    "950", "430",
				    swfVersionStr, xiSwfUrlStr,
				    flashvars, params, attributes);
    };

    pub.updateProfileSpottedLink = function(pID) {
        var hash = '#profilespotted/';
        $('#map_sidebar_title a').attr('href', 'nw_type_map.aspx?show=' + 'browse&codename=' + (pID || ''));
        $('#map_sidebar_content a').attr('href', 'nw_type_map.aspx?show=' + 'mark&codename=' + (pID || ''));
    }

    /****** PRIVATE FUNCTIONS *******/

    var switchMode = function(newMode) {

        //  INIT
        var oldMode = setting.currentMode;
        setting.currentMode = newMode;

        if (oldMode != newMode) {
            //  DECONSTRUCT OLD & CONSTRUCT NEW
            $("#" + oldMode + "_panel").animate(
                {
                    opacity: 0
                },
                setting.transSpeed,
                function() {
                    $("#" + oldMode + "_panel").hide();
                    switchMode_constructNewMode(newMode);
                }
            );

            if (pemco[oldMode] && pemco[oldMode].deconstruct) {
                pemco[oldMode].deconstruct();
            }
        }

        setting.somethingIsLoaded = true;
    }

    var switchMode_constructNewMode = function(newMode) {

        $("#" + newMode + "_panel").show();
        $("#" + newMode + "_panel").animate({ opacity: 1 }, setting.transSpeed, function() { this.style.filter = "none"; });
        //eval("pemco." + newMode + ".construct();");

        if (pemco[newMode] && pemco[newMode].construct)
            pemco[newMode].construct();

    }

    var populateLinks = function() {
        pemco.ajax.getPemcoProfileLinks(function(res) {

            // populate sidebar
            $(".more_profiles_list").html(res.html);
        });
    }

    /****** ACTIONS *******/

    //$('.our').live('mousedown', pub.carouselMode);
    //$('.your').live('mousedown', pub.userCarouselMode);
    //$('.commercial').live('mousedown', pub.commercialsMode);
    //$('.profileSpottedLink').live('mousedown', pub.profileSpottedMode);
    //$('.createProfileLink').live('mousedown', pub.createProfileMode);
    //$('.userCarouselLink').live('mousedown', pub.userCarouselMode);
    $('.create_profile').live('mousedown', pub.createProfileMode);
    //$('.my_profiles').live('mousedown', pub.myProfilesMode);
    //$('.calendar').live('mousedown', pub.getEventCalendarMode);

    // Not Clicked Functions
    $(function() {
        var $parents;
        var acts = {};

        if (pemco.tray != undefined) {
            acts['#tray'] = pemco.tray.lower;
        }

        if (pemco.user != undefined) {
            acts['#lightbox'] = pemco.user.closeLightboxPopup;
        }

        if (pemco.iframe != undefined) {
            acts['#iframe-wrapper'] = pemco.iframe.deconstruct;
        }

        $(document.body).click(function(e) {
            $parents = $(e.target).parents();
            for (var sel in acts) if (!$parents.is(sel)) acts[sel]();
        });
    });

    $(document).ready(populateLinks);

})(jQuery);




pemco.log = function() {
	console.dir(pemco);
}
