/// <reference path="jquery.intellisense.js"/>

/**
 * Datacard IDS User Interface
 */ 
var DATACARD = {

    /**
     * Delay before panel's reveal in miliseconds
     */         
    navigation_delay: 45,
    
    /**
     * Time of panel's scaling in miliseconds
     */          
    navigation_scaling: 150,

    /**
     * IDs of tabs on the current page.
     */
    tabIds: new Array(),

    /**
     * Init UI functions
     */         
    init: function () {   
    
        $(".tabs .tabs-nav").tabs();
        DATACARD.expandableContents();
        DATACARD.updateProductsNumbers();
		DATACARD.sidebarPromo();
        DATACARD.formFieldsFocus();
        DATACARD.lastTabWidth();
        DATACARD.topSearch();
        DATACARD.navigation();
        DATACARD.checkBrowseProductsTab();
        DATACARD.setTabLinks();
        DATACARD.designASolutionHelp();
        DATACARD.clickable();
        DATACARD.checkAutoCompleteLength();        

        // DATACARD.rollovers();
	
		// Commented out the following, causing page loading slowdown and 502 errors on these images - aalgaat 11/15/2010
        /*
        DATACARD.preloadImages(["/images/bg/search-text-focus.gif", 
                                "/images/bg/panel1.gif", 
                                "/images/bg/panel2.gif", 
                                "/images/bg/panel3.gif", 
                                "/images/bg/panel4.gif", 
                                "/images/bg/panel5.gif",
                                "/images/bg/top-tools-panel1.gif",
                                "/images/bg/top-tools-panel2.gif",
                                "/images/bg/top-tools-panel3.gif",
                                "/images/buttons/help.png",
                                "/images/buttons/help-h.png",
                                "/images/buttons/reset.png",
                                "/images/buttons/reset-h.png"
                                ]); 
		*/
		
        if($.browser.msie){
            DATACARD.fixIE6flicker(true);
        }       
        
        
        $('a.anchor').remove().prependTo('body');
        
    },


    checkAutoCompleteLength: function()
    {
        $('#autocompletesubmit').click(function()
        {
			if($('#suggest1').attr('value').length <2 || $('#suggest1').attr('value')=="Enter Product Name or Number"){
				alert("Please select a valid product name or number");
				return false;
			}
			
        });
    },
    
    setTabLinks: function()
    {
        $('a.tab-link').click(function()
        {
            document.location = $(this).attr('href');
            DATACARD.checkBrowseProductsTab();
        });
    },
    
    /**
     * Expandable products content zones
     */
    expandableContents: function () {
        
        /**
         * These settings can affect the overall performance of the page -
         * longer duractions provide better animation effects, but seem
         * to degrade performance more.
         */
        // Duration of page scrolling to expandable zone
        var scrolling_duration = 40; //500
        
        // Duration of closing all expandable zones at once except current
        var scrolling_offset = -20; //-20
        
        // Duration of expanding expandable zone
        var expanding_duration = 100; //400
        
        // Duration of closing all expandable zones at once except current
        var collapsing_all_duration = 100; //1200
        
        // Expanding / Collapsing Content Zones - used when user clicks on header bar of current zone
        $('.expandable h2 a,.tabs-products .top-nav li a, .panel1 .list1 a, .panel1 .list2 a').not(".home").click(function () {
            var link = $(this);            
			var id = link.attr('href').replace("#", "");

			// have to split out href because of IE7 which gets full url, not just querystring
			var id_array = link.attr('href').split('#')
			if(id.length > 0){
				id = id_array[1];
			}

            var expandable = $('#'+id);
            var is_closed = expandable.hasClass("expandable-closed");
            var expandable_inner = expandable.find('.expandable-inner');

			// highlight top bookmarks
            $('.tabs-products .top-nav li a').removeClass('current');
			var expandableHeader = $('#' + id+"Header");


            // Target expandable is closed - close all others expandables, scroll to target and open it including additional products
            if (is_closed) {
           		expandableHeader.addClass("current");  
				$('.expandable-inner').parent().addClass("expandable-closed");
				$('.expandable-inner').slideUp(collapsing_all_duration);

				// following line needed to slide down first grouping
				expandable_inner.slideDown(expanding_duration);

				expandable.removeClass("expandable-closed");                
            // Target expandable is opened - just close it
            } else {
            	expandableHeader.removeClass("current");  
				$('.expandable-inner').parent().addClass("expandable-closed");
				$('.expandable-inner').slideUp(collapsing_all_duration);
				expandable.addClass("expandable-closed");
            }
            
            return false;
        });
        
        
        // [ADD] Expanding / Collapsing Content Zone for How to Design a Solution instructions
        $('.instructions-expandable h2 a').click(function () {
            var link = $(this);
            var expandable = $(link).parents('.instructions-expandable');
            var expandable_inner = expandable.find('.instructions-expandable-inner');
            var is_closed = expandable.hasClass("instructions-expandable-closed");

            // Target expandable is closed - open it
            if (is_closed) {
                // Do not use scroll for Opera until jQuery.ScrollTo is fixed, then this condition can be removed
                if ($.browser.opera) {
                     expandable_inner.slideDown(expanding_duration);
                     expandable.removeClass("instructions-expandable-closed");
                } else {
                    $.scrollTo(link, scrolling_duration, {
                        offset: scrolling_offset, 
                        onAfter: function () {
                            expandable_inner.slideDown(expanding_duration);
                            expandable.removeClass("instructions-expandable-closed");
                        }
                    });
                }            
            // Target expandable is opened - just close it
            } else {
                expandable_inner.slideUp(expanding_duration, function callback() {
                    expandable.addClass("instructions-expandable-closed");
                });
            }
            return false;
        });
        
        // Expanding / Collapsing Content Zones - used when user clicks on View all link
        $('.expandable .view-all a').click(function () {
            
            var id = $(this).parents('.expandable').attr("id");
            var expandable = $('#' + id);
            var additional_products = expandable.find('.additional-products');
            
            // Do not use scroll in Opera until jQuery.ScrollTo is fixed, then this condition can be removed
            if ($.browser.opera) {
                  additional_products.slideDown(expanding_duration, function callback() {
                      expandable.find('.view-all').slideUp(expanding_duration);
                  });
            } else {
                $.scrollTo($(expandable), scrolling_duration, {
                    offset: scrolling_offset, 
                    onAfter: function () {
                        additional_products.slideDown(expanding_duration, function callback() {
                            expandable.find('.view-all').slideUp(expanding_duration);
                        });
                    }
                });
            }
            return false;
        });        
        

    },
    
    /**
     * Update products number in all content zones
     * Call this functions when you insert products to content zones      
     */         
    updateProductsNumbers: function () {
        $('.expandable').each(function (i) {

            var number;
            
            if ($(this).find('.product').length) {
                number = $(this).find('.product').length;
            } else {
                number = $(this).find('.item').length;
            }
            
            $(this).find('.number').text(number);

        });
    }, 
	
	sidebarPromo: function() {
        $('img.next').bind('click', function() {
			$('div.selected').fadeOut('fast');
			$('div.selected').next().fadeIn('slow');
            $('div.selected').removeClass('selected').next().addClass('selected');
        });
        $('img.prev').bind('click', function() {
			$('div.selected').fadeOut('fast');
			$('div.selected').prev().fadeIn('slow');
            $('div.selected').removeClass('selected').prev().addClass('selected');
        });
    }, 
    
    /**
     * Correct last tab width so it is aligned when it's selected
     */         
    lastTabWidth: function () {
        var tabs_width = 0;
        
        $('.tabs-nav > li').each(function (i) {
            tabs_width += $(this).width();
        });
        
        if (tabs_width < 669) {
            var padding_right = 17 + (669 - tabs_width);
            $('.tabs-nav #last-tab a').css('padding-right', padding_right)
        }
    },

    /**
     * Clear text inputs, selects and textareas set border color on focus 
     */          
    formFieldsFocus: function () {
        
		 if ($('body').hasClass("dealer-form")==false) {        
        
			$(':text:not(.search-text)').addClass('text-input');

			// Selects
			$('select').focus(function () {
				$(this).addClass('focus');
			}); 

			// Inputs and textareas
			$(':text:not(.search-text), textarea').each(function (i) {

				var initial_value = $(this).attr('value');

				$(this).focus(function () {
					$(this).addClass('focus');

					// Clear only initial value
					if ($(this).attr('value') === initial_value) {
						$(this).attr('value', '');
					}
				}); 
			});

			// Restore border line color on focus
			$(':text, select, textarea').blur(function () {
				$(this).removeClass('focus');
			});
		}
    },
    
    /**
     * Clear top search input on focus and set white background
     */          
    topSearch: function () {
       $('#top-tools-search .search-text').focus(function () {
            $(this).addClass('search-focus');
            $(this).attr('value', '');
        }); 
    },

    /**
     * Main and Top Tools Navigation
     */
    navigation: function () {
       // $("#nav > li, .top-tools #tool1, .top-tools #tool2, .top-tools #country-select").not("#nav03").not("#nav04").hoverIntent({
 		$("#nav > li, .top-tools #tool1, .top-tools #tool2, .top-tools #country-select").hoverIntent({       
            sensitivity: 7,
            interval: DATACARD.navigation_delay,
            over: expand,
            timeout: 0,
            out: collapse                
        });

        function expand() {
            var panel = $(this).find(".panel");
            
             /* IE 6 select bug fix - set height of iframe dynamically */
            panel.find('iframe').height(panel.height());
            
            panel.css('z-index', 150);
            $(this).addClass("hover");
            panel.slideDown(DATACARD.navigation_scaling);
        }
        
        function collapse() {
            var panel = $(this).find(".panel");
            panel.css('z-index', 100)
            panel.slideUp(DATACARD.navigation_scaling, function callback() {
                $(this).parent().removeClass("hover");
            });
        }
    },

    designASolutionHelp: function () {
    
		$('.design-solution #top-radio a.help').hover(
			function() {
				$('.design-solution #top-radio .balloon').parent().css('z-index',14000);
				$(this).parent().children('.balloon').fadeIn('250');
			},
			function() {
				$(this).parent().css('z-index', 0);
				$(this).children().css('z-index', 0);	
				$(this).parent().children('.balloon').fadeOut('100');
			}
  		);  
    

		$('.design-solution a.help').hover(
			function() {				
				$(this).parent().children('.balloon').fadeIn('250');
			},
			function() {
		        $(this).parent().children('.balloon').fadeOut('100');
			}
		);

    },    
    
    /**
     * Fix background image flicker in IE6
     */         
    fixIE6flicker: function (fix) {
        try {
            document.execCommand("BackgroundImageCache", false, fix);
        } catch(err) { }
    },  

    /**
     * make urls for divs and images
     */
    clickable: function () {

		var url=window.location;  
		var anchor=url.hash; //anchor with the # character  
		var anchor2=url.hash.substring(1); //anchor without the # character 

    
		$(".clickable").click(
			function()
			{
				 window.location = $(this).attr("href");
				 
				if(anchor == "#applications"){
					$('#applicationsSubNav').show();
					$('#applicationsTab').click();
				}
				
				if(anchor == "#industry-topics"){
					$('#industrytopicsSubNav').show();
					$('#industryTopicsTab').click();
				} 				
				 
				 event.preventDefault(); 
				 return false;
			}
		);		


		if(anchor == "#industry-topics" || anchor == "#case-studies" || anchor == "#why-datacard" || anchor == "#white-papers"){
			$('#applicationsSubNav').hide();
			$('#industrytopicsSubNav').show();
			$('.subTabContent').show();  
		}
		
		if(anchor == "" || anchor == "#overview"){
			$('.subTabContent').show();  
		}		

		if(anchor == "#applications"){
			$('#industrytopicsSubNav').hide();
			$('#applicationsSubNav').show();
			$('.subTabContent').show();  
		}
        
        // Financial Market specific code
        
        $('#financialTabs #industryTopicsTab').click(function()
        {
			$('#industrytopicsSubNav').show();
			$('#applicationsSubNav').hide();
			$('#relatedProductsContent').hide();  			
        });	

        $('#financialTabs #applicationsTab').click(function()
        {
			$('#applicationsSubNav').show();
			$('#industrytopicsSubNav').hide();
			$('#relatedProductsContent').hide();  			
        });	
        
        $('#financialTabs #overviewTab,#financialTabs #caseStudiesTab,#financialTabs #whitePapersTab,#financialTabs #whyDatacardTab').click(function()
        {
			$('#relatedProductsContent').hide();  			
			$('.tabs-subnav').hide();
        });        

        $('#financialTabs #related-products-id').click(function()
        {
			$('.subTabContent').hide();  
			$('#relatedProductsContent').show();  
        });
        
        $('#financialTabs .back-to-applications').click(function()
        {		
			$('.subTabContent').show();  
			$('#relatedProductsContent').hide();  
        });	


        $('#financialTabs #applicationsTab,#financialTabs #whyDatacardTab,#financialTabs #overviewTab,#financialTabs #caseStudiesTab,#financialTabs #whitePapersTab,#financialTabs #whyDatacardTab').click(function()
        {
			$('.subTabContent').show();  
        });  
        

		// Generic Market code

		// used to show contents of hidden related products tab and hide applications tab in markets pages
        $('#marketTabs #related-products-id').click(function()
        {
			$('#applications').hide();      
			var applicationTitle = $(this).attr("href").split('#');
			$('.back-to-related-products-link').html(applicationTitle[1]);
			$('#related-products').show();  
        });			

		// used to hide contents of hidden related products tab and show applications tab in markets pages
        $('#marketTabs .back-to-applications').click(function()
        {
			$('#related-products').hide();
			$('#applications').show();   
			$('#applicationsTab').click();
        });	

		if(anchor == "#market-drivers"){
			$('#marketDriversTab').click();
		}

	},
    
    /**
     * Rollovers buttons
     */
    rollovers: function () {
    
        $('.rollover').hover(
            function () {
                var rollover_src = $(this).attr('src').replace(/.png/, '_over.png');
                if ($.browser.msie) {
                     $(this).css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + rollover_src + "\', sizingMethod='scale');");
                } else {
                     $(this).attr('src', rollover_src);
                }
            },
            function () {
                $(this).attr('src', $(this).attr('src').replace(/_over.png/, '.png'));
            }
        );
     },
    
    /**
     * Preload images
     * @param {Array} images array with names of images   
     */               
    preloadImages: function (images) {
        for (var i = 0; i < images.length; i++) {
            var image = new Image();
            image.src = "/"+images[i];
        }
    },
    
    /** 
     * Determine if we should jump to content within a tab on the current page. If so, highligth tab and jump down.
     * this is a work around for linking deep into a page when the desired id is hidden under a second tab.
     * this functionality is specific to the browse products page.
     * Added 8/25/2008 ef / bswing
     */
    /**
     * Attempts to match a fragment identifier to an expandable box in the current page
     * and if found, opens that expandable box.
     */
    checkBrowseProductsTab:function()
    {
        // Get the fragment identifier from the location (if present).
        var loc = document.location.toString();
        var start_index = loc.indexOf("#");
        var end_index = loc.length;

        if(start_index > -1) // A fragment identifier exists
        {
            // Now attempt to find a matching expandable box in the page. 
            var anchor_text = loc.substring(start_index,end_index);
            var numTabIds = DATACARD.tabIds.length;
            var isMatch = false;
            var isMatchTabIndex = 0;
            
            var browseAllRegex = new RegExp("browse-all");
            var isBrowseAllLink = browseAllRegex.test(anchor_text);
            
            if (isBrowseAllLink)
            {
                // Browser check        
	            var minMSIEVersion = 8;
	            var uBrowser;
	            var uVersion;
	            jQuery.each(jQuery.browser, function(i, val)
                {
                    if ((i == "msie") && (val == true))
                    {
                        uBrowser = i;
                    }
                    else if ((i == "mozilla") && (val == true))
                    {
                        uBrowser = i;
                    }
                    else if ((i == "safari") && (val == true))
                    {
                        uBrowser = i;
                    }
                    else if ((i == "opera") && (val == true))
                    {
                        uBrowser = i;
                    }
                    
                    uVersion = new Number(jQuery.browser.version.substr(0,3));
                });
                
                if (anchor_text == "#standard-browse-all")
                {
                    // Open the corresponding parent tab.
                    $(".tabs .tabs-nav").tabs('select', 0);
                    // Reset the body links.
                    $('#standard-products .top-nav li a').removeClass('current');
                    // Expand contents -
                    // If IE7, handle as default page entry (IE7 has trouble w/transparent images)
                    if (!((uBrowser == 'msie') && (uVersion == 7)))
                    {
                        $('#standard-products .expandable').each(function()
                        {
                            $(this).find('.expandable-inner').slideDown(0);
                            $(this).removeClass("expandable-closed");
                        });
                    }
                }
                else if (anchor_text == "#enterprise-browse-all")
                {
                    // Open the corresponding parent tab.
                    $(".tabs .tabs-nav").tabs('select', 1);
                    // Reset the body links.
                    $('#enterprise-products .top-nav li a').removeClass('current');
                    // Expand contents - 
                    // If IE7, handle as default page entry (IE7 has trouble w/transparent images)
                    if (!((uBrowser == 'msie') && (uVersion == 7)))
                    {
                        $('#enterprise-products .expandable').each(function()
                        {
                            $(this).find('.expandable-inner').slideDown(0);
                            $(this).removeClass("expandable-closed");
                        });
                    }
                }
            }
            else
            {
                // Attempt to find a matching expandable box.
                for (var i = 0; i < numTabIds; i++)
                {
                    if ($(anchor_text).parents(DATACARD.tabIds[i]).length > 0)
                    {
                        isMatch = true;
                        isMatchTabIndex = i;
                        break;
                    }
                }

                if (isMatch == true) // Found a matching expandable box
                {
                    // Open the corresponding parent tab.
                    $(".tabs .tabs-nav").tabs('select', isMatchTabIndex);
                    
                    // Trigger the same click event as the body links (within the tabs).
                    var a = $('.top-nav li a[href=' + anchor_text + ']');
                    a.click();
                }
            }
        }
    }    
}

function showhide(id){
	if (document.getElementById){
		obj = document.getElementById(id);
		if (obj.style.display == "none"){
			obj.style.display = "";
		} else {
			obj.style.display = "none";
		}
	}
}

/* Knowledge Center Modal*/
    
var page = {

    /**
    * init()
    */
    init: function () {
        // Set the "click" event handler for modal links.
        $(".cardFeatureLink,.cardGalleryLink,.videoLink,.workflowLink").click(function () {
       
            var href = $(this).attr("href");
			
			// remove jsessionid from href
            href = href.replace(/;jsessionid=([A-Z0-9]*)/,"");
            // remove extra needed left side forward slash form beginning or url, extra slash is needed because of included droplets on right side and the full path that occurs from the include
            href = href.replace(/\//,"");
            
            // Parse the feature name and slide index out of the "href" attribute.
            //var strings = href.split("?");
            //var querystring = strings[1];
            var strings = href.split("-");
            //var featureID = page.getQuerystringParameter(querystring, "f");
            //var slideIndex = page.getQuerystringParameter(querystring, "n");
            var featureID = strings[0];
            var slideIndex = strings[1]; 
            //var appPage = strings[2];             

            // Call to open the modal.
            page.modal.open(featureID, slideIndex-1);
            // Prevent the click event from causing a page refresh.
            return false;
        });

        // Set the "click" event handler for the close button. 
        $("#modalContainer .close").click(function () {
            page.modal.close();
        });

        // Set the "click" event handler for the layer underneath the modal.
        $("#modalTrigger").click(function () {
            page.modal.close();
        });

        // Set "resize" event handler for the modal - repositions the modal.
        $(window).resize(function () {
            page.modal.onWindowResize();
        });
        
		if(jQuery.browser.msie && jQuery.browser.version == 6){
			$("body").height($(document).height()+150+"px");        
		}
    },

    /**
    * Returns the value of the name-value pair specified by the input "name"
    * @param querystring The querystring string, without the "?"
    * @param name The name of the name-value pair to get the value from
    * @return string
    */
    getQuerystringParameter: function (querystring, name) {
        var value = "";
        var nameValuePairs = querystring.split("&");
        var nameValuePairsCount = nameValuePairs.length;
        for (var i = 0; i < nameValuePairsCount; i++) {
            var strings = nameValuePairs[i].split("=");
            if (strings[0] === name) {
                value = strings[1];
                break;
            }
        }
        return value;
    }
}

page.modal = {

    // Absolute path to the directory containing the card features assets.
    featuresPath: "/icf/",

    /**
    * Closes the modal.
    */
    close: function () {
        $("#modalWrapper").animate({ opacity: 0.0 }, 1000, function () {
            $("#modalWrapper").css("display", "none");
        });

        // Remove the "legacy" #flashContainer" element - a new "#flashContainer"
        // will be added to the DOM when a card featured is launched.
        $("#flashContainer").remove();

        $("div#overlay").animate({ opacity: 0.0 }, 1000, function () {
            $("div#overlay").remove();
        });
    },

    /**
    * Opens the modal.
    * @param slideID The ID (number) of the slide to display when the SWF loads
    */
    open: function (featureID, slideIndex) {
        // Determine if current browser is Firefox < 3.
        var isFirefoxLessThan3 = false;
        if ($.browser.mozilla) {
            var numbers = $.browser.version.split(".");
            if (numbers[1] < 9) {
                isFirefoxLessThan3 = true;
            }
        }

        // Insert the semi-transparent page overlay layer into the DOM (but not
        // in Firefox 2 (or lesser versions)).
        if (!isFirefoxLessThan3) {
            $("<div />").attr("id", "overlay").appendTo("body").show();
        }

        var swf = page.modal.featuresPath + "datacard_slideshow.swf";

		var flashHeight = "546";
		var flashWidth = "858";

        // Set the appropriate title image to display.
        switch (featureID) {
            case "driverslicense":
                showHideModalHeader("#title-drivers-license-features-tour");
                googleTrackingPrefix = "cardfeatures";
                break;
            case "fips":   
                showHideModalHeader("#title-fips-features-tour");
                googleTrackingPrefix = "cardfeatures";
                break;
            case "nationalid":         
                showHideModalHeader("#title-national-id-features-tour");                
                googleTrackingPrefix = "cardfeatures";
                break;
            case "laserpassport":
                showHideModalHeader("#title-passport-features-tour");
                googleTrackingPrefix = "cardfeatures";
                break;
            case "accesscontrol":
                showHideModalHeader("#title-access-control-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "creditdebit":
                showHideModalHeader("#title-credit-debit-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "directmail":
                showHideModalHeader("#title-direct-mail-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "employeeid":
                showHideModalHeader("#title-employee-id-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "giftprepaid":
                showHideModalHeader("#title-gift-prepaid-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "loyalty":
                showHideModalHeader("#title-loyalty-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "membership":
                showHideModalHeader("#title-membership-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break; 
            case "university":
                showHideModalHeader("#title-university-gallery");
                googleTrackingPrefix = "cardgalleries";                
                break;
            case "wfadvocate":
                showHideModalHeader("#title-advocate-workflow");
                googleTrackingPrefix = "workflows";                
		        swf = page.modal.featuresPath + featureID + "/EndToEnd_Advocate.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                
                break;
            case "wfdriverslicense":
                showHideModalHeader("#title-driverslicense-workflow");
                googleTrackingPrefix = "workflows"; 
		        swf = page.modal.featuresPath + featureID + "/EndToEnd_DriversLicense.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                  
                break;
            case "wffinancial":
                showHideModalHeader("#title-financial-workflow");
                googleTrackingPrefix = "workflows";   
		        swf = page.modal.featuresPath + featureID + "/EndToEnd_Financial.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                  
                break;
            case "wfmilitaryid":
                showHideModalHeader("#title-militaryid-workflow");
                googleTrackingPrefix = "workflows";  
		        swf = page.modal.featuresPath + featureID + "/EndToEndGovernmentGID.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                  
                break;
            case "wfnationalid":
                showHideModalHeader("#title-nationalid-workflow");
                googleTrackingPrefix = "workflows"; 
		        swf = page.modal.featuresPath + featureID + "/EndToEndGovernmentNatID.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                  
                break;
            case "wfpassport":
                showHideModalHeader("#title-passport-workflow");
                googleTrackingPrefix = "workflows";  
		        swf = page.modal.featuresPath + featureID + "/EndToEndGovernmentPASS.swf"; 
				flashHeight = "544";
				flashWidth = "850";	                  
                break;
            case "sd260features":
                showHideModalHeader("#title-sd260-features");
                googleTrackingPrefix = "cardgalleries";
                break;
            case "sd360features":
                showHideModalHeader("#title-sd360-features");
                googleTrackingPrefix = "cardgalleries";
                break;                
            case "cd800features":
                showHideModalHeader("#title-cd800-features");
                googleTrackingPrefix = "cardgalleries";
                break;
            case "mxdfeatures":
                showHideModalHeader("#title-mxd-features");
                googleTrackingPrefix = "mxdfeatures";
                break;
            default:            	
                showHideModalHeader("#title-"+featureID);
                googleTrackingPrefix = featureID;  
		        swf = page.modal.featuresPath + "video/content/"+featureID+".swf";      
				flashHeight = "500";
				flashWidth = "790";
	            break;                
        }
        
		// make call to Google Page Tracker
		if ( typeof( window[ '_gaq' ] ) != "undefined" ) {
			// old non-asynchronous way
			//pageTracker._trackPageview("/"+googleTrackingPrefix + "/" +featureID);
			
			// new asynchronous way
			 _gaq.push(['_trackPageview','/'+googleTrackingPrefix + '/' +featureID])
		}        

        // We will re-embed the SWF to ensure the updated slideID value is
        // available within the SWF.

        // Remove the "legacy" #flashContainer" element.
        $("#flashContainer").remove();

        // Add a new #flashContainer element.
        $("<div />").attr("id", "flashContainer").appendTo("#modalContainer").show();

        // Insert whatever HTML content to serve as the alternate content for
        // the SWF (probably instructions to get Flash Player).
        var html = '';
        html += '<p><a href="http://get.adobe.com/flashplayer/">Install Adobe Flash Player</a></p>';
        $("#flashContainer").html(html);

        // Prepare the configuration for the SWF embed.
        var flashvars = {};
        var params = { x_features_path: "", x_feature_directory: "", start_slide: 0 };
        var attributes = {};

        // Update params with global configuration values.
        params.x_features_path = page.modal.featuresPath;
        // Update params with values parsed from the in-page link.
        params.x_feature_directory = featureID;
        params.start_slide = slideIndex;

        // Use SWFObject to embed the SWF.
        
        swfobject.embedSWF(swf, "flashContainer", flashWidth, flashHeight, "8.0.0", flashvars, params, attributes);
        
        
        //swfobject.embedSWF(swf, "flashContainer", flashWidth, flashHeight, "8.0.0", flashvars, params, attributes);

		//AC_FL_RunContent(
		//	'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',

		//	'src', swf,

		//	'movie', 'video-1'
		//	); //end AC code



        // Initiate the actions to display the modal.
        $("#modalWrapper").css("height", $(document).height() + "px");
        $("#modalTrigger").css("height", $(document).height() + "px");
        $("#modalContainer").css("top", $(window).scrollTop() + "px");
        this.setPosition();
        $("#modalWrapper").css("display", "block");
        $("#modalWrapper").animate({ opacity: 1.0 }, 1000, function () { });
    },

    onWindowResize: function () {
        $("#modalWrapper").css("height", $(document).height() + "px");
        $("#modalTrigger").css("height", $(document).height() + "px");
        
        // Re-center the modal.
        this.setPosition();
    },

    /**
    * Centers the modal in the page.
    */
    setPosition: function () {
        var windowCenter = $(window).width() * .5;
        var modalCenter = 442;
        var offset = windowCenter - modalCenter;
        $("#modalContainer").css("left", offset + "px");
    }
}


function showHideModalHeader(modalName){
	// show selected modal title images
	$(modalName).show();
	$(modalName).animate({opacity: 1.0}, 0);
	// hide all other modal title images
	$('#title-advocate-workflow,#title-driverslicense-workflow,#title-financial-workflow,#title-militaryid-workflow,#title-nationalid-workflow,#title-passport-workflow,#title-videosd260,#title-videogovernmentsolutions,#title-videomx6000overview,#title-videomxdmaileroverview,#title-videomaxsysoverview,#title-videoattachersystems,#title-videoattachergift,#title-videoartistafin,#title-videoartistagov,#title-videogv300overview,#title-videogv300inserter,#title-videogv500carrier,#title-videomj7500overview,#title-videomxdliteoverview,#title-drivers-license-features-tour,#title-card-features-tour,#title-fips-features-tour,#title-national-id-features-tour,#title-passport-features-tour,#title-credit-debit-gallery,#title-university-gallery,#title-gift-prepaid-gallery,#title-access-control-gallery,#title-employee-id-gallery,#title-loyalty-gallery,#title-membership-gallery,#title-direct-mail-gallery,#title-sd260-features,#title-videopb6500,#title-sd360-features,#title-videosd360overview,#title-cd800-features,#title-mxd-features,#title-videogogreen,#title-videoinstantissuance,#title-videocorporateoverview,#title-videomx6000modularity,#title-videocd800,#title-videomx6000barrel,#title-videoenhancedmxd,#title-videomx1000government,#title-videomx1000financial,#title-videosecureissuanceanywhere').not(modalName).animate({opacity: 0.0}, 0).hide();
}

function openWindow(url){
	var re = /\?/g;
	url =  url.replace(re, "---");
	re = /\&/g;
	url =  url.replace(re, "___");
	re = /\=/g;
	url =  url.replace(re, "~~~");
	remote = window.open('/includes/redirect.jhtml?url='+url,'datacardredirect','width=10000'+',height=10000'+'menubar=yes,toolbar=yes,resizable=yes,scrollbars=yes,location=yes,directories=yes,status=yes,left=50,top=50');
	remote.focus();
}

DatacardHomeSlide = {

	CurrentSlide: null,
	SlidesSrc: null,
	Slides: null,
	Navs: null,
	R: null,
	BtnNext: null,
	BtnBack: null,
	Interval: null,
	AutoPlay: true,

	Init: function () {


		// define slides

		// TODO: Hrefs need to be defined 

		this.SlidesSrc = [];

		var slide1 = [{ path: "/images/home_page/home_slideshow/banner_1.jpg", x: 0, y: 0, w: 932, h: 328, href: null, title: null },
						{ path: "/images/home_page/home_slideshow/banner_1_text.png", x: 70, y: 133, w: 411, h: 72, href: null, title: "" }
					 ];

		var slide2 = [{ path: "/images/home_page/home_slideshow/banner_2.jpg", x: 0, y: 0, w: 932, h: 328, href: null, title: null },
					  { path: "/images/home_page/home_slideshow/banner_2_text.png", x: 70, y: 109, w: 440, h: 116, href: "http://www.secureissuanceanywhere.com", title: "" }
					 ];

		var slide3 = [{ path: "/images/home_page/home_slideshow/banner_3.jpg", x: 0, y: 0, w: 932, h: 328, href: null, title: null },
					  { path: "/images/home_page/home_slideshow/banner_3_text.png", x: 70, y: 37, w: 411, h: 124, href: null, title: null },
					  { path: "/images/home_page/home_slideshow/banner_3_link_1.png", x: 70, y: 196, w: 279, h: 20, href: "/financial/credit-and-debit-cards", title: "Credit & Debit Cards" },
					  { path: "/images/home_page/home_slideshow/banner_3_link_2.png", x: 70, y: 220, w: 276, h: 20, href: "/financial/gift-and-prepaid-cards", title: "Gift Cards & Prepaid Cards" },
					  { path: "/images/home_page/home_slideshow/banner_3_link_3.png", x: 70, y: 244, w: 276, h: 20, href: "/retail/affinity", title: "Co-Branded/Affinity Cards" }
					 ];

		var slide4 = [{ path: "/images/home_page/home_slideshow/banner_4.jpg", x: 0, y: 0, w: 932, h: 328, href: null },
					  { path: "/images/home_page/home_slideshow/banner_4_text.png", x: 70, y: 37, w: 411, h: 124, href: null },
					  { path: "/images/home_page/home_slideshow/banner_4_link_1.png", x: 70, y: 196, w: 276, h: 20, href: "/government/travel-id-and-passport", title: "Travel IDs & Passports" },
					  { path: "/images/home_page/home_slideshow/banner_4_link_2.png", x: 70, y: 220, w: 276, h: 20, href: "/government/national-id", title: "National IDs" },
					  { path: "/images/home_page/home_slideshow/banner_4_link_3.png", x: 70, y: 244, w: 276, h: 20, href: "/government/drivers-license", title: "Driver's Licenses" }
					 ];

		var slide5 = [{ path: "/images/home_page/home_slideshow/banner_5.jpg", x: 0, y: 0, w: 932, h: 328, href: null },
					  { path: "/images/home_page/home_slideshow/banner_5_text.png", x: 70, y: 37, w: 411, h: 124, href: null },
					  { path: "/images/home_page/home_slideshow/banner_5_link_1.png", x: 70, y: 196, w: 276, h: 20, href: "/corporate/employee-ids", title: "Employee ID Cards" },
					  { path: "/images/home_page/home_slideshow/banner_5_link_2.png", x: 70, y: 220, w: 276, h: 20, href: "/education/college-and-university-campus-cards", title: "College & University Campus Cards" },
					  { path: "/images/home_page/home_slideshow/banner_5_link_3.png", x: 70, y: 244, w: 276, h: 20, href: "/healthcare/patient-and-visitor-id-cards", title: "Patient & Visitor UD Cards" }
					 ];

		this.SlidesSrc.push(slide1, slide2, slide3, slide4, slide5);

		// create SVG or VML object
		this.R = Raphael("homepage-holder", 932, 328);

		this.CurrentSlide = 0;

		this.Slides = [];

		// draw slides
		for (var s = 0; s < this.SlidesSrc.length; s++) {

			var assets = this.SlidesSrc[s];
			var set = new Array();
			for (var p = 0; p < assets.length; p++) {
				var a = assets[p];
				var img = this.R.image(assets[p].path, assets[p].x + (932 * s), assets[p].y, assets[p].w, assets[p].h);
				img._offset = assets[p].x;
				img._href = assets[p].href;

				if (assets[p].href == null) {
					img.mouseover(this.ShowArrows).mouseout(this.HideArrows);
				} else {
					img.attr({ cursor: "pointer", title: assets[p].title });
					img.click(function () {
						document.location = this._href;
					});
				}
				set.push(img);
			}
			this.Slides.push(set);
		}

		// create nav buttons along bottom
		this.Navs = [];
		var a = Math.floor(this.Slides.length / 2) * 20;
		var b = (932 / 2) - a;

		for (var s = 0; s < this.Slides.length; s++) {

			var opac = (s == 0) ? 1 : .3;
			var n = this.R.circle(b + (s * 40), 305, 5).attr({ stroke: null, fill: "#fff", opacity: opac, cursor: "pointer" });
			n._index = s;
			n.click(this.Go); 
			this.Navs.push(n);
		}

		// create next and back buttons
		this.BtnNext = this.R.image("/images/home_page/home_slideshow/arrow_next.png", 891, 150, 44, 42).attr({ cursor: "pointer" }).mouseover(this.NextOver).show().click(this.Go);
		this.BtnNext._index = -1;

		this.BtnBack = this.R.image("/images/home_page/home_slideshow/arrow_back.png", -3, 150, 44, 42).attr({ cursor: "pointer" }).mouseover(this.BackOver).hide().click(this.Go);
		this.BtnBack._index = -2;

		// roundy corners 
		var bot = this.R.image("/images/home_page/home_slideshow/mask.png", 0, 0, 932, 5).clone();

		if (Raphael.type == "VML") {
			// differnt x,y for IE 8 and 7
			bot.attr({ y: 322,x: -1 }).transform("r180");
		} else {
			bot.attr({ y: 323 }).transform("r180");
		}

		// auto play
		this.Interval = setInterval(this.Go, 10000, "auto");

	}
	,
	Go: function (auto) {

		// go to slide. called on click events and autoplay

		var d = DatacardHomeSlide;

		// determine which slide to go to

		if (auto != "auto" || auto != undefined) {
			clearInterval(d.Interval);
			d.Interval = setInterval(d.Go, 8000, "auto");
		}
		if (auto == "auto" || auto == undefined) {
			d.CurrentSlide++;
			if (d.CurrentSlide >= d.Slides.length) {
				d.CurrentSlide = 0;
			}
		} else if (this._index == -1 && d.CurrentSlide == d.Slides.length - 1) {
			return;
		} else if (this._index == -2 && d.CurrentSlide == 0) {
			return;
		} else if (this._index == -1) {
			d.CurrentSlide++;
		} else if (this._index == -2) {
			d.CurrentSlide--;
		} else {
			d.CurrentSlide = this._index;
		}

		// determine offset
		var b = d.CurrentSlide * 932 * -1;

		for (var s = 0; s < d.Slides.length; s++) {

			//position all my elements
			var elements = d.Slides[s];
			var _x = b + (932 * s);
			for (var e = 0; e < elements.length; e++) {
				elements[e].animate({ x: _x + elements[e]._offset }, 1000, "<>");
			}

		}

		// update nav highlight
		for (var n = 0; n < d.Navs.length; n++) {
			if (n != d.CurrentSlide) {
				//console.log("not current");
				d.Navs[n].animate({ opacity: .3 }, 500, "<>");
			} else {
				// console.log("current");
				d.Navs[n].animate({ opacity: 1 }, 500, "<>");
			}
		}

		if(d.CurrentSlide==(d.Slides.length - 1)){
			// if last, then hide next button
			d.BtnBack.show();
			d.BtnNext.hide();
		}
		else if(d.CurrentSlide==(0)){
			// if first, hide back button and show next
			d.BtnNext.show();
			d.BtnBack.hide();
		}
		else{
			// if neither first or last, check if both buttons are visible, then show if not
			d.BtnNext.show();
			d.BtnBack.show();
		}

	}
}
