﻿/************************************************************** 
    UI FUNCTIONS
    Date: 07/02/2009
 **************************************************************/

//GLOBAL VARS
var floatNFollowYPoint = null;
var floatNFollowDiv = null;
var enableFloatNFollow = false;
var enableScrollToTabs = true;
var iComHostname = "";
var corpHostname = "";



//Main method for initializing Illumina main ui components.
//Do not init if not needed!
$(function() {
    if ($('#header').length) {
        $.ajax({
            type: "GET",
            url: "/prebuilt/includes/header_full.ilmn",
            //cache: true,
            dataType: "html",
            success: function(res){
                $("#header").html(res);
            },
            error: function(xhr, status, error){
                //don't do anything - defaults to minimal header
            },
            complete: function(){
                initILMN();
            }
        });
    }	
    else {
        initILMN();
    }
    
    //Hooks to generic show/hide elements
    $('.toggleChild').hide();    
    $('.toggleParent').click(function(event){
        $(this).next('.toggleChild').slideToggle(200);
    });
});

function initILMN() {
    //[NOTE!!!] Remove this once we go live
    if (location.hostname != "www.illumina.com") {
        $('a[href^="http://www.illumina.com/forms/quote_request.ilmn"]').each(function() {
            $(this).attr('href', $(this).attr('href').replace('www.illumina.com','www-test.illumina.com'));
        });
    }

    initShop();
    
    //for layout with optional divs, adjust width
    var featureDivs = $('.optionalCols3or4 .featuredContent')
    if (featureDivs.length == 3) {
        var featureDivsWidth = featureDivs.width()*4;
        featureDivs.css('width',(featureDivsWidth/3));
    }

	if (enableFloatNFollow && $('#floatNFollow').length) { 
		floatNFollowDiv = $('#floatNFollow');
        floatNFollowYPoint = parseInt(floatNFollowDiv.css("top").substring(0,floatNFollowDiv.css("top").indexOf("px")));
    
        initFloatNFollow();
	}
    
    if ($('#mainNav').length) {
	    initMainNav();	
	}
	if ($('[class^=tabbedSlider] .tabs a').length) { 
	    initTabbedSlider();
	}
	
    initModalIFrameFromUrl();

	//DO NOT MOVE ABOVE TABBED SLIDER OR WEIRD BUG
	if ($('a[class^=modalLink]').length) {
	    initModalBox();
	}
	initModalCallbackShow(); //Needed here for close links within iframe
	
	if ($('div.addthis_toolbox').length) {
	    //initAddThis();
	}
    
    $('#ilmn_search_words').focus(function() {
        if ($(this).val()=="Search")
            $(this).val("");
    });
    $('#ilmn_search_btn').click(function() {
        if ($('#ilmn_search_words').val()=="Search"){
            $('#ilmn_search_words').val("");
            $('#ilmn_search_words').focus();
            return false;}
        if ($('#ilmn_search_words').val()==""){
            $('#ilmn_search_words').focus();
            return false;}    
        return true;   
    });
    
    initPageTools();
}

function toggleChildShowAll() {
    $('.toggleChild').show();
}

function initShop() {
    iComHostname = "https://icom.illumina.com/";
    corpHostname = "http://www.illumina.com/";
    
    if (location.hostname != "www.illumina.com") {
        corpHostname = "http://www-test.illumina.com/";
    }
        
    var addToCartUrl = iComHostname + "Cart/AddAndShow/?catalogid={0}&quantity={1}&redirecturl={2}";
    var quoteUrl = corpHostname + "forms/quote_request.ilmn?qitem={0}&quantity={1}";

    $('select[id^=icom_product_id]').change(function () { //update catalog num
        $(this).parent().find('span[id^=icom_catalog_num]').text($(this).val());
    });
    $('input[id^=icom_product_qty]').change(function() { //validate quantity
        var qty  = parseInt($(this).val());
        $(this).val((isNaN(qty) || qty < 1) ? 1 : qty);              
    });
    $('a[href=#icom_add_to_cart]').click(function () { //cart link
        var p = $(this).parent();
        var id = p.find('select[id^=icom_product_id]:first').val();
        var qty =  p.find('input[id^=icom_product_qty]:first').val();
        location.href = addToCartUrl.replace("{0}", id).replace("{1}", qty).replace("{2}", window.location);
        return false;
    });  
    $('a[href=#icom_get_quote]').click(function () { //quote link
        var p = $(this).parent();
        var id = p.find('select[id^=icom_product_id]:first').val();
        var qty =  p.find('input[id^=icom_product_qty]:first').val();
        location.href = quoteUrl.replace("{0}", id).replace("{1}", qty);
        return false;
    });
}

function initModalIFrameFromUrl() {
     
    var location = window.location.href; //?modal=/dna/omni&modalsize=800x600
    var i = location.indexOf('modal=');
    var j = location.indexOf('%26modalsize=');
    if (i > -1) {
        var iframeUrl = (j > -1) ? location.substring(i+6,j) : location.substring(i+6);
        var size = (j > -1) ? location.substring(j+13) : '800x600';
        var dimensions = size.split('x');
        var w = parseInt(dimensions[0]);
        var h = parseInt(dimensions[1]);
        if (!w || !h || (w > 960) || (h > 760)) { //validate size
            w = 800;
            h = 600;
        }
        var modalClass = "modalLink[" + w + "," + h + "]";
        
        //validate url is coming from illumina or else we do not display modal!!!
        if (iframeUrl.length > 1 && 
            (iframeUrl.indexOf('http://www.illumina.com') == 0 
            || iframeUrl.indexOf('https://icom.illumina.com') == 0)
            || iframeUrl.indexOf('/') == 0) {
        
            var ch = (iframeUrl.indexOf('?') > -1) ? '&' : '?';
            var modalLink = "<a id='modalIFrameFromUrl' href='" + iframeUrl + ch + "iframe' class='" + modalClass + "'></a>";
            $('body').append(modalLink); 
        }          
    }
}


function initAddThis() {
    $('.custom_button, .hover_menu').mouseenter(function() {        
        $('.hover_menu').fadeIn('fast');        
        $('.custom_button').addClass('active');        
        $(this).data('in', true);        
        $('.hover_menu').data('hidden', false);    
    }).mouseleave(function() {        
        $(this).data('in', false);        
        setTimeout(hideMenu, delay);    
    });  
          
    var delay = 400;    
    function hideMenu() {        
        if (!$('.custom_button').data('in') && !$('.hover_menu').data('in') && !$('.hover_menu').data('hidden')) {            
            $('.hover_menu').fadeOut('fast');            
            $('.custom_button').removeClass('active');            
            $('.hover_menu').data('hidden', true);
        }
    }  
}

function initPageTools() {

    var customFeedbackBtn = $('#ilmn_button_feedback');
    if (customFeedbackBtn.length) {
        customFeedbackBtn.attr('href', customFeedbackBtn.attr('href') + "&pageurl=" + location.pathname);
    }

    $('#ilmn_button_print').click(function() {
        window.print();
        return false;
    });            
                        
    var shareUrl = "/share.ilmn?title={1}"; //share.ilmn?page={0}&title={1}                  
    shareUrl = shareUrl.replace('{1}', $('title').html());
    $('#ilmn_button_share').attr('href', shareUrl);
    
}

function initFloatNFollow() {

    if (enableFloatNFollow) {
        if (floatNFollowDiv) {
            $(window).scroll(function () { 
                var offset = floatNFollowYPoint+$(document).scrollTop()+"px";
                floatNFollowDiv.animate({top:offset},{duration:500,queue:false});
            });
        } 
    }
 
}

function initMainNav() {

    var speed = 400;
    
    var navLinks = $("#mainNavBar a");
    var panels = $(".mainNavPanel");
    var panelContentLists = $(".panelSectionContent > ul");

    panelContentLists.hide();
    
    function ie6Fix(mode) { /*fix floating select boxes in IE6*/
        if ($.browser.msie && $.browser.version < 7) {
            if (mode == 'hide')
                $('.hideOnNavAction').hide();
            else
                $('.hideOnNavAction').show();
        }
    }
    
    //show panel when top links hovered - hoverIntent
    $("#mainNavBar a").hoverIntent(
        
        //hover in effect
        function(event){    
            var panelToDropDown = $(this).next('div');
            if (panelToDropDown.is(":hidden")) {
                //reset
                panels.hide();
                panelContentLists.hide();
                navLinks.removeClass("current");
                
                panelToDropDown.slideDown();
                $(this).addClass("current");  
            }
            ie6Fix('hide'); 
	    },
	
	    //hover out effect
	    function(event){}
	
	);
	$("#mainNav").hover(
        
        //hover in effect
        function(event){},
	
	    //hover out effect
	    function(event){
            panels.hide();
            panelContentLists.hide();
            navLinks.removeClass("current");
            ie6Fix('show');
	    }
	
	);
	
    //expand list contents when subtopic moused over
    $(".panelSectionContent > a").mouseover(function(event) {
        var panelToExpand = $(this).next();
        if (panelToExpand.is(":hidden")) {
            panelContentLists.slideUp(speed); //reset the rest
            panelToExpand.slideDown(speed);
        }
	});
}


function initModalBox() { 
    var speed = 1;
    var showOverlay = true;
    var opacity = 0.30;
    
    var modalWidth;
    var modalHeight;    
    function modalLinkGetSize() {
        var classVal = $(this).attr('class');
        if (classVal.length == 9) { //use default
            modalWidth=800;
            modalHeight=600;
        }
        else {
            var widthByHeight = $(this).attr('class').substring(10); //class="modalLink[width,height]"
            var dimensions = widthByHeight.split(',');
            modalWidth= parseInt(dimensions[0]);
            modalHeight= parseInt(dimensions[1].substring(0,dimensions[1].length-1)); //remove last "]"
        }
    }
    
    var modalLinks = $('a[class^=modalLink]');
    modalLinks.each(function() {

        modalLinkGetSize.call(this);
        
        $(this).fancybox({ 
            'hideOnContentClick': false,
            'zoomSpeedIn': speed, 
            'zoomSpeedOut': speed, 
            'overlayShow': showOverlay,
            'overlayOpacity': opacity,
            'frameWidth': parseInt(modalWidth),
            'frameHeight': parseInt(modalHeight),
            'callbackOnShow': initModalCallbackShow,
            'callbackOnClose': initModalCallbackClose //on modal close, the window scroll listener seems disabled - reenable
        }); 
    });
    
    //if "#name" is passed in the url, trigger link with id=name or href=#name
    var modalIFrameFromUrl = $('#modalIFrameFromUrl');
    if (modalIFrameFromUrl.length) {
        $('#modalIFrameFromUrl').trigger('click'); 
    }
    else if (location.hash.length>1) { //page.ilmn#shortcut
        var linkID = $('a' + location.hash + '[class^=modalLink]'); //check id
        if (linkID.length == 0)
            linkID =  $('a[href$=' + location.hash + '][class^=modalLink]'); //check href (used for hidden divs)
        if (linkID.length)
            linkID.trigger('click');  
    }
}
function initModalCallbackShow() {
    $(".modalClose").click(function (){ 
        //$.fn.fancybox.close();
        parent.top.$('#fancy_close').trigger('click');
        return false;
    }); 
}
function initModalCallbackClose() {
    $("#fancy_content").empty(); //stop flash
    //initFloatNFollow(); 
}

function initTabbedSlider() {

    var $panels = $('[class^=tabbedSlider] .scrollContainer > div.tabsPanel');
    var $container = $('[class^=tabbedSlider] .scrollContainer');
    var $tabs = $('[class^=tabbedSlider] .tabs a');

    // if false, we'll float all the panels left and fix the width of the container
    var horizontal = true;
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }

    // collect the scroll object, at the same time apply the hidden overflow
    var $scroll = $('[class^=tabbedSlider] .scroll').css('overflow', 'hidden');

    // handle nav selection
    function selectNav() {
            
        $tabs.removeClass('selected');        
        $(this).addClass('selected');
    }
    $tabs.click(selectNav);

    // go find the tabs link that has this target and select the nav
    function trigger(data) {
        var el = $('[class^=tabbedSlider] .tabs').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }

    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;

    var scrollOptions = {
        target: $scroll,    // the element that has the overflow
        items: $panels,     // can be a selector which will be relative to the target
        tabs: $tabs,

        // selectors are NOT relative to document, i.e. make sure they're unique
        prev: 'img.left', 
        next: 'img.right',
        
        axis: 'xy',         // allow the scroll effect to run both directions
        onAfter: trigger,   // our final callback
        offset: offset,
        duration: 500,      // duration of the sliding effect

        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports the indexed next and previous scroll along with hooking 
    // in to our tabs.
    $('.slider').serialScroll(scrollOptions);    
    // apply localScroll to hook any other arbitrary links to trigger the effect
    $.localScroll(scrollOptions);
    // if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 to hide scroll effect on the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);
    
    //adjust tab panel height dynamically
    function animateHeight() {
        // var nextPanelID = $(this).attr('href');
        var urlBits = $(this).attr('href').split('#');
        var nextPanelID = '#' + urlBits[1];
        var nextPanelHeight = $(nextPanelID).height();
        $scroll.animate({
            height: (nextPanelHeight+40)
        });
        
        if (enableFloatNFollow) {
            //if changing tab panel height and there is a floated box, make sure to adjust as necessary
            var scrollBottom = $(this).offset().top + $(this).height() + nextPanelHeight;
            var fNf = $('#floatNFollow');
            if (fNf.length) {
                var fNfBottom = fNf.offset().top + fNf.height();
                if (scrollBottom < fNfBottom) 
                    fNf.animate({top:$(this).offset().top-200},{duration:500,queue:false});
            }
        }
    }
    
    $tabs.click(function() {
        animateHeight.call(this);
    });         
    $('[class^=tabbedSlider] .tabsLink').click(function() {
        animateHeight.call(this);
    }); 
    
    //SELECT DEFAULT TAB
    //Priority:
    //1. Url hash
    //2. Tab with class="selected"
    //3. Tab panel with id="tabs_panel_default"
    //4. First tab
    if (location.hash.length>1) {
        trigger({ id : location.hash.substr(1) });
        $.scrollTo('[class^=tabbedSlider] .tabs',{duration:400});
    } else {
        var defaultSelected = $('[class^=tabbedSlider] .tabs a.selected');
        if (defaultSelected.length) {
            defaultSelected.click();
        }
        else {
            defaultSelected = $('#tabs_panel_default');
            if (defaultSelected.length == 0) {
                $('[class^=tabbedSlider] .tabs a:first').click();         
            }
            else {
                $scroll.animate({
                    height: (defaultSelected.height()+40)
                });
            }
        }
    }
    
    if ($('#tabsPartialBorder').length) {
        var partialBorder = $('#tabsPartialBorder');
	    var tabs = $('[class^=tabbedSlider] ul.tabs a');
	    if (tabs.length < 6) {
	        var tabsWidth = 0, leftMargin = 0, rightMargin = 0;
	        tabs.each(function() {
	            leftMargin = parseInt($(this).css("margin-left"));
	            rightMargin = parseInt($(this).css("margin-right")); 
	            tabsWidth += $(this).width() + leftMargin + rightMargin;
	        });

	        partialBorder.css('left',tabsWidth+parseInt(partialBorder.css('left')));
	        partialBorder.css('width',partialBorder.width()-tabsWidth);	
	    } 
	    else {
	        partialBorder.hide();
	    }
	}
}