﻿var HPI = HPI || {};
HPI.JDS = HPI.JDS || {};
HPI.JDS.Utils = HPI.JDS.Utils || {};
HPI.JDS.lightbox = function(opts){
    $.fancybox({
			    'transitionIn'	:	'elastic',
			    'transitionOut'	:	'elastic',
			    'type'			:  	opts.type || 'ajax',
			    'href'			: 	opts.content,
			    'speedIn'		:	600, 
			    'speedOut'		:	200, 
			    'overlayShow'	:	true,
			    'width'			:	opts.width,
			    'height'		:	opts.height,
			    'padding'		: 	0,
			    'margin'		:	0,
			    'autoDimensions':	true,
                'centerOnScroll':   true,
			    'scrolling'		: 	'no',
			    'onComplete' : opts.onComplete || function(){}
    });
};
HPI.JDS.Utils = {
	initFlash : function(){
	    if(typeof(swfobject)!=='undefined'){
	        if(this.getFlashVersion() < 10){
	            $('#marquee a, .marquee_subpage a').show();
	        }else{
		        swfobject.embedSWF("includes/swf/standup_list.swf", "marquee", "150", "160", "10.0.0", "includes/swf/expressInstall.swf",{},{wmode:"transparent",menu:"false",allowScriptAccess:"always"});
		        swfobject.embedSWF("includes/swf/standup_list_subpage.swf", "marquee_subpage", "210", "250", "10.0.0", "includes/swf/expressInstall.swf",{},{wmode:"transparent",menu:"false"});
		        //absolutely reference this one so that 2nd tier pages can use
		        swfobject.embedSWF("/includes/swf/tree_flip.swf", "tree_flip", "108", "206", "10.0.0", "includes/swf/expressInstall.swf",{},{wmode:"transparent",menu:"false"});
		    }
	    }
	},
	getFlashVersion : function(){
	    var version = '0,0,0';
        // ie
        try {
            try {
                // avoid fp6 minor version lookup issues
                // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
                var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                try { axo.AllowScriptAccess = 'always'; }
                catch(e) { return '6,0,0'; }
            } catch(e) {}
            version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
        // other browsers
        } catch(e) {
            try {
                if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
                    version = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
                }
            } catch(e) {}
        }
        return version.split(',').shift();
    },
    getInternetExplorerVersion : function(){
        // Returns the version of Internet Explorer or a -1
        // (indicating the use of another browser).
        var rv = -1; // Return value assumes failure.
        if (navigator.appName == 'Microsoft Internet Explorer'){
            var ua = navigator.userAgent;
            var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null)
              rv = parseFloat( RegExp.$1 );
        }
        return rv;
    }

};

HPI.JDS.UI = {
    attachDomBehaviors : function(){
		$('.social_media_tab_content #tab_link').toggle(function() {
				$('.social_media_tab_content').animate(
					{top:'-=46'}, 
					1000,
					'easeOutBounce');
				$('.social_media_tab_bg').animate(
					{top:'-=46'}, 
					1000,
					'easeOutBounce', function() {
					    $('.social_media_tab_content a').css('display', 'block');
					});
			},
			function(event) { 
				$('.social_media_tab_content a').css('display', 'none');
				$('.social_media_tab_content a#tab_link').css('display', 'block');
				$('.social_media_tab_content').animate(
				    {top:'+=46'}, 
				    500,
				    'easeInCubic');
				$('.social_media_tab_bg').animate(
				    {top:'+=46'}, 
				    500,
				    'easeInCubic');
		});

		// Update Counter
		$(document).ready(function () {
			$.get('handler/counter', function(data) {
				$('#counter').html(data);
			});
		});

        $('#submit_to_lightbox').click(function() {
            HPI.JDS.UI.openStandUpModal();
        });
        
        // Rollover Tooltips for Social Media
        $('.social_media_static a, .social_media_bottom a').hover(function () {
                $(this).children().css('display', 'block');
            },
            function () {
                $(this).children().css('display', 'none');
            }
        );
        
        // Bookmark/Favorite Link
        $('#link_star').jFav();
        
	},
    openStandUpModal : function(){
        //create stand up modal form data custom object
        var buildFormData = function(){
            return {
		        submitUrl : 'handler/save_people',
	            fields : {
		            firstName : {
			            value : $('#f_name').val(),
			            maxLength : $('#f_name').attr('maxlength'),
			            errorField : $("label[for='f_name'] .error")
		            },
		            lastName : {
			            value : $('#l_name').val(),
			            maxLength : $('#l_name').attr('maxlength'),
			            errorField : $("label[for='l_name'] .error")
		            },
		            email : {
			            value : $('#email_address').val(),
			            maxLength : $('#email_address').attr('maxlength'),
			            type : "email",
			            errorField : $("label[for='email_address'] .error")
		            },
		            zip : {
			            value : $('#zip').val(),
			            maxLength : $('#zip').attr('maxlength'),
			            type : "zip",
			            errorField : $("label[for='zip'] .error")
		            }
	            },
	            onComplete : function(){
    	            $.cookie('jds_sign_up', 'success', {path: '/', expires: 1});
                    $('.reg_launch').css('display', 'none');
                    $('.reg_complete').css('display', 'block');
	            }
            }
        };
        
        //Private object
        var oOpts = {
            content : "includes/reg_forms/standup.htm",
            width : 491,
            height : 371,
            onComplete : function(){
                HPI.JDS.UI.splitName(); // Autofills name fields based on original input
                $('#f_name').alpha();
                $('#l_name').alpha();
                $('#f_name, #l_name').keypress(function(event) {
                    if(event.keyCode==95){
                        return false;
                    }
                }); 
                $('#zip').numeric({allow:"-"});
		        $('#standup_submit').click(function() {
		            $(this).removeClass('submit_static');
		            $(this).addClass('submit_processing');
		            var formData = buildFormData();
                    HPI.JDS.FORM.validate(formData,this);
                });
		    }
        }
        HPI.JDS.lightbox(oOpts);
    },
    preloadImages : function(img_paths){
        var imgs = [];
        for(var i=0, imgP_len=img_paths.length; i<imgP_len; i++) {
            imgs[i] = new Image(); 
            imgs[i].src = img_paths[i];
        }
    },
    toggleSelectedNavLink : function(){
        var oNav = $('.header ul li a')
        $.each(oNav,function(){
            var curLink = $(this);
            if(window.location.href.indexOf(curLink.attr('id')) != -1){
                curLink.addClass(curLink.attr('id')+'-selected');
                curLink.removeAttr('id');
            }
        });
    },
    updateCounter:function(){
        //create digit array
        var aHtmlDigits = $('.counter span');
        var counter_len = 7;
        var aDigits = [];
        var count = 0;
        var newCount = 0;
        
        $.each(aHtmlDigits,function(){
            count+=$(this).html();
        });
        
        //set new count
        newCount = parseInt(count,10)+1;
        //convert back into array
        aDigits = newCount.toString().split('');
        var aDigits_len = aDigits.length;
        //Determine start index of digit placement in counter
        var startDigitIndex = counter_len - aDigits_len; 
        
        for(var i=startDigitIndex;i<counter_len;i++){
            aHtmlDigits[i].innerHTML = aDigits[i-startDigitIndex];                    
        }
    },
    splitName : function(){
        var fullname = $('#fullname').val();
        fullname = fullname.replace(/^\s+|\s+$/g,""); // Remove leading/trailing spaces
        //fullname = fullname.substr(0,8);
        
        if(fullname != "") {
            var spaceIndex = fullname.indexOf(' ');
            if (spaceIndex > 0) {
                var first = fullname.substring(0, spaceIndex);
                var last = fullname.substring(spaceIndex+1);
                $('#f_name').val(first);
                $('#l_name').val(last);
            } else {
                $('#f_name').val(fullname);
            }
        }
    }
};

HPI.JDS.FORM = {
    validate: function (formData, target) {
        var errCount = 0;
        var formElements = {};

        for (var fieldName in formData.fields) {
            if (formData.fields.hasOwnProperty(fieldName)) {
                var isValid = true;
                var field = formData.fields[fieldName];
                if(field.errorField){ //if field is required
                    if (field.value == "" || field.value < field.maxLength) {
                        errCount += 1;
                        isValid = false;
                    }
                
                    if (field.type == "email") {
                        if (!this.validateEmail(field.value)) {
                            isValid = false;
                            errCount += 1;
                        }
                    }
                    if (field.type == "zip") {
                        if (!this.validateZip(field.value)) {
                            isValid = false;
                            errCount += 1;
                        }
                    }
                }
                //Store form element name and value pairs for ajax form submission
                formElements[fieldName] = field.value;

                if (!isValid) {
                    $(field.errorField).css('display', 'inline');
                } else {
                    $(field.errorField).css('display', 'none');
                }
            }
        }

        if (errCount == 0) {
            // ajax call
            $.ajax({
                url: formData.submitUrl,
                data: formElements,
                cache: false,
                error: function (data, textStatus, errorThrown) {
                    $(target).removeClass('submit_processing');
                    $(target).addClass('submit_static');
                    alert("There was an error processing your form. Please try again later.");
                },
                complete: function (xml, textStatus) {
                    if (textStatus == "success") {
                        formData.onComplete();
                        HPI.JDS.UI.updateCounter();
                        $(target).removeClass('submit_processing');
                        $(target).addClass('submit_static');
                        if (typeof (marquee) !== 'undefined') {
                            var ieVersion = HPI.JDS.Utils.getInternetExplorerVersion();
                            if (ieVersion >= 7 || ieVersion == -1) {
                                marquee.reset(); // Call to AS to reset scrolling list if marquee is present and not IE 6
                            }
                        }
                        $.fancybox.close();
                    }
                }
            });
        } else {
            $(target).removeClass('submit_processing');
            $(target).addClass('submit_static');
        }
    },
    validateEmail: function (str) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return reg.test(str);
    },
    validateZip: function (zip) {
        var reg = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
        return reg.test(zip);
    }
};

$(document).ready(function(){
    HPI.JDS.UI.toggleSelectedNavLink();
    HPI.JDS.Utils.initFlash();
	HPI.JDS.UI.attachDomBehaviors();
    //applies anywhere the standup textbox appears
    $('#fullname').alpha().keypress(function(event) {
        if(event.keyCode==95){
            return false;
        }
    }); 
	HPI.JDS.UI.preloadImages(['/images/nav_join_fight_ro.gif', '/images/nav_our_shop_ro.gif', '/images/nav_our_sponsors_ro.gif', '/images/tooltips.png']);
});

