
$(function() {

    initAccordion();
    initCarousel();
    initDropdown();
    initPdf();
    initMyFiles();
    initCollapsibleHeaders();
    //initCarousel();

});

function initPdf(){
    var targets = [];
    // extension gets what class applied
    var ext_class = {
        'pdf' : 'pdf',
        'doc' : 'word',
        'docx': 'word',
        'xls' : 'excel'
    };

    for(t in ext_class) targets.push("a[href$='." + t + "']");

    // Assign a PDF icon or DOC icon beside documents
    $(targets.join(',')).not('.results .controls a').not('#umbrella a').not('.widget a').each(function(){

        if($(this).find('img').length == 0){

            var full_href = $(this).attr('href');
            for(t in ext_class){
                if(full_href.indexOf('.' + t) != -1){
                    var type = ext_class[t];
                    $(this).addClass(type);
                }
            }

            $(this).click(function(){
                Tracker.files( Workspace.DownloadTrackingPath + escape(full_href.split('/').reverse()[0]));
            });
        }
    });

}

function initTouOverlay(){
        var dims = getPageSize();
        var overlayOffset = (dims[2] - $("#tou-overlay").width())/2;

        $("#tou-overlay").overlay({

		onBeforeLoad: function() {
                    overlayTou = this;
                    $('#overlay_iframe').attr('src',Workspace.Index+'/agree-terms-of-use');
		},

                top: "10%",
                left: overlayOffset,
                fixed: true,

                mask: {
                        color: '#000',
                        loadSpeed: 200,
                        opacity: 0.5
                },

                closeOnClick: false,

                load: overlayLoad

        });
}

function initCarousel(){
    window.api = $(".carousel");

    if ( typeof(api) != "undefined" && api.length) {

        $(".carousel").scrollable({
            circular: true
        }).navigator({
            navi: ".carousel-thumbs",
            naviItem: 'a'
        });

        if(api.data("scrollable").getSize()>1){
            $(".carousel").autoscroll({
                autoplay: true,
                api: true,
                interval: 5000
                });
        }

        $('.carousel-thumbs li:first a').addClass('active'); // set first item as active

        $(".carousel").hover(
            function() {       // In
                pauseCarousel(true)
            },
            function() {       // Out
                playCarousel(true)
            }
        );

    }
}

var Tracker = {
    files: function(url){
        console.log(url);
        _gaq.push(['_trackPageview', url]);
    }
};
var pageTracker={_trackPageview:function(url){Tracker.files(url); }};

/**********************************************
 * Main Nav Dropdown
 *
 **********************************************/

function initDropdown(){
    if(Workspace.DropdownEnabled){
        $('#top-menu > li:has(ul)').addClass('has-dropdown').find('a:first').wrapInner('<span class="downarrow" />');
        $('#top-menu > li').hover(showLargeMenu, hideLargeMenu);
        $('#top-menu .large-menu-wrapper').width( $('#top-menu').width() );
        $('#top-menu .large-menu').each( function(){
            $(this).find('.col:first').addClass('first');
            $(this).find('.col:last').addClass('last');
        });
    }
}

function showLargeMenu(){
    var newPosition = $('#top-menu li:first').position().left - $(this).position().left;
    $(this).addClass('active').find('.large-menu-wrapper:first').show().css('left', +newPosition+'px');
}

function hideLargeMenu(){
    $(this).removeClass('active').find('.large-menu-wrapper:first').hide();
}
/**********************************************
 * Collabsible headers / Accordion
 *
 **********************************************/

function initAccordion(){
    if(Workspace.AccordionEnabled){
         $(".accordion").tabs(".accordion-pane", {tabs: 'h3', effect: 'slide', initialIndex: null});
         $(".accordion-pane").hide();
    }
}

function initCollapsibleHeaders() {
    $('#resources-rx-for-change-faqs .centre-column h4').addClass('accordionHeader headerCollapsed');
    $('#resources-rx-for-change-faqs .centre-column h4').nextUntil(':header').hide();
    $('#resources-rx-for-change-faqs .centre-column h4').bind('click', toggleCollapsibleHeaders);
}
function toggleCollapsibleHeaders() {
    //find everything up to the next <hX> tag and toggle() it
    $(this).toggleClass('headerCollapsed');
    $(this).toggleClass('headerExpanded');
    $(this).nextUntil(':header').toggle();
}


/**********************************************
 * Carousel
 *
 **********************************************/
/**
 * Called on overlay open and carousel hover */
function pauseCarousel( hovering ) {
    if ( typeof(api) != "undefined" ) {
        api.pause();
    }
}

/**
 * Called on overlay close and carousel hover off */
function playCarousel( hovering ) {
    if ( typeof(api) != "undefined" ) {
        api.play();
    }
}

/**********************************************
 * My Files
 *
 **********************************************/

function initMyFiles(){

    if(Workspace.MyfilesEnabled){

        $("#main .pdf").not('.deletefile').not('.filename').not('nav.side-menu a').each(function(){
            var full_href = $(this).attr('href');
            var full_text = $(this).text();
            if ($(this).next().not('.add-to-collection')) {
                $(this).after('<a href="'+Workspace.RootUrl+'/cart/add?filename='+escape(full_href)+'&title='+escape(full_text)+'" class="add-to-collection add-to-collection-square" title="'+escape(Workspace.terms.myfiles_add)+'">'+Workspace.terms.myfiles_add+'</a>');
            }
        });

        $('#myfiles .deletefile').live('click', cartDeleteItem);
        $('#myfiles .btn-downloadall').bind('click', cartDownloadAll);
        $('#myfiles .btn-deleteall').bind('click', cartEmpty);
        $('a.add-to-collection').live('click', cartAddItem);

        /**
         * My files Dropdown */
        $('.myfiles-flyout').css('top', ($('#myfiles-btn').height()+8)+'px');
        $('#myfiles-btn').click(function(){
            $('.myfiles-flyout').toggle();
            $('#myfiles').toggleClass('active');
             return false;
        });

    }    
}

function showMyFiles(){
    $(this).addClass('active').find('.myfiles-flyout').show();
}

function hideMyFiles(){
    $(this).removeClass('active').find('.myfiles-flyout').hide();
}

/**
 * Document Cart */
function cartAddItem(){
    var addUrl = $(this).attr('href');
    var queryString = addUrl.split('?')[1].split('&');
    var params = new Array();
    for (var i=0; i<queryString.length; i++) {
        var tmp = queryString[i].split('=');
        params[tmp[0]] = tmp[1];
    }

    var anchorTag = $(this);

    $.getJSON(addUrl, function(data){
        if (data.success) {
            if (data.duplicate == true) {
                return false;
            }
            var removeUrl = cart_url_remove + '?filename=' + params['filename'];
            var fileUrl = params['filename'];
            var counter = Number($('#myfiles span.num').text());
            $('#myfiles span.num').text(counter + 1);
            //TODO add file in overlay
            $('.no-document-msg').hide();
            $("div.myfiles-flyout ul.files").append(
                '<li>'
                + '<a href="' + removeUrl + '" class="deletefile pdf">'+Workspace.terms["myfiles_delete"]+'</a>'
                + '<a href="' + fileUrl + '" class="filename pdf">' + unescape(params['title']) + '</a>'
                + '</li>'
            );
            $('#umbrella-user-controls .btn-downloadall').show();
            $('#umbrella-user-controls .btn-deleteall').show();
            anchorTag.after('<span class="myfiles-file-added">'+Workspace.terms["myfiles_file_added"]+' <a href="#top">'+Workspace.terms["myfiles_goto_my_files"]+'</a></span>');
            anchorTag.parent().find('.myfiles-file-added a').click(function(){$('#myfiles-btn').click();return true;});
            anchorTag.parent().find('.myfiles-file-added').css("backgroundColor","#ffffff").animate({"backgroundColor":"#ffff99"},{queue:true, duration:200}).animate({"backgroundColor":"#fff"},{queue:true, duration:2000});
        }
    });
    return false;
}

function cartDeleteItem(){
    var toRemove = $(this).parent();
    var url = $(this).attr('href');
    $.getJSON(url, function(data) {
        if (data.success) {
            toRemove.remove();
            var counter = Number($('#myfiles span.num').text());
            $('#myfiles span.num').text(counter - 1);
            if (counter - 1 == 0) {
                $('#umbrella-user-controls .btn-downloadall').hide();
                $('#umbrella-user-controls .btn-deleteall').hide();
            }
        }
    })
    return false;
}
function cartDownloadAll(){
    window.location = cart_url_download;
    return false;
}
function cartEmpty(){
    $.getJSON(cart_url_empty, function(data) {
        if (data.success) {
            $('#myfiles ul.files li').remove();
            $('#myfiles span.num').text('0');
            $('#umbrella-user-controls .btn-downloadall').hide();
            $('#umbrella-user-controls .btn-deleteall').hide();
        }
    })
    return false;
}


/******************
 * Miscellaneous helpers
 */

function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

