// AIS
/*globals jQuery, window */
/*
	minify to reduce filesize of published sci.js

	requires: jquery-1.3.1.min.js
	
	naming conventions:
		camelCaseFunctions 
		CapitalisedCamelCaseConstructors  
		under_score_variables 
		hyphenated-css-classes-and-ids
		$jquery_objects start with a $
	
	beware! jQuery doesn't like to compete with window.onload used by other scripts
*/



// flash globals
var AC_FL_RunContent = 0,
    DetectFlashVer = 0,
    requiredMajorVersion = 9,
    requiredMinorVersion = 0,
    requiredRevision = 115; //24?
// eo: flash

var ais = ais || {};

jQuery.noConflict();
(function ($) {

    ais.initSearch = function (search_selector_str) {
	    $(search_selector_str).each(function () {
		    var search_field_text, $search_field; /* $submit_btn; */
			
			// get search_field, search inside if needed
			$search_field = $(this).is("input[type='text']") ? $(this) : $("input[type='text']", this);
			
			//search_field_text = $(this).val();
		    search_field_text = $search_field.attr("title"); /* fixes f5 refresh ff3 bug */
    		
		    $search_field
			    .focus(function () {
				    if (this.value === search_field_text) {
					    this.value = '';
					    $(this).addClass("focussed");
				    }
			    })
			    .blur(function () { 
				    if (this.value === "") {
					    this.value = search_field_text;
					    $(this).removeClass("focussed");
				    }
			    });
			  
//            $submit_btn = $(this).nextAll("input[type='submit']").get(0);
//            $(this).keypress(function (e) {
//                if (e.which === 13) {
//                    $submit_btn.click();
//                };
//            });
			 					 
	    });	
    };
      
//    ais.initSearch = function (search_id) {
//	    var $search_field, search_field_text;
//	    $search_field = $(search_id);
//	    search_field_text = $search_field.val();
//	    $search_field
//		    .focus(function () {
//			    if (this.value === search_field_text) {
//				    this.value = '';
//				    $search_field.addClass("focussed");
//			    }
//    	    })
//		    .blur(function () { 
//			    if (this.value === "") {
//				    this.value = search_field_text;
//				    $search_field.removeClass("focussed");
//			    }
//		    });
//    };

    ais.jsCSS = function () { 
	    // enable javascript dependent css
	    $('body').addClass('js');
    };

    ais.prepLinkRels = function (message) {
	    // fix _blank rel=external
	    message = message || "(Opens in new window)";
    	
	    //$('A[@rel~="external"]')
	    $("a[rel*='external']")
		    .click(function () {
			    window.open($(this).attr('href'));
			    return false;
		    })
		    .each(function () {
			    var title = $(this).attr("title");
			    if (!title) {
				    $(this).attr("title", message);
				    // this.setAttribute("title", message);
			    }
		    });
    };
    		
    ais.prepJournals = function () {
	    // requires ais.jsCSS
	    /*
	    assumes:
	    .journals
		    .journal
			    :header
			    img
			    div
    			
	    builds:
	    .journals
		    .journal
			    a > img
		    div #journal-n
	    */
    	
	    $('.journals')
		    .each(function (i) {
			    var $journals;
			    $journals = $(this);
			    $journals
				    // .attr('id', 'journals-' + i)
				    .children('.journal') // .journals > .journal					  
				    .each(function (j) {
					    var $journal, $header, $img, $div, $back_to_top;
					    $journal = $(this);
					    $header = $journal.children(':header');
					    $img = $journal.children('img');
					    $div = $journal.children('div');
					    if (!$header || !$img || !$div) { // test these var exist!
						    return false;
					    }
					    $div
						    .attr('id', 'journal-' + i + '-' + j)
						    .addClass('journal-contents');
    					
					    // put goto top link at end of div 
					    $back_to_top = $('<a>' + ais.text.backtotop + '</a>');
					    $back_to_top.attr('href', '#core'); //'#journals-' + i);
					    $back_to_top.addClass('back-to-top');
					    $div.append($back_to_top);
    					
					    $journals.append($div);
					    $div.hide();
					    $header
						    .remove()
						    .children('a')
						    .eq(0)
						    .appendTo($journal)
						    .prepend($img)
						    .click(function () {
							    if ($journal.hasClass('open')) {
								    $journal.removeClass('open');
								    $div.slideUp('slow');
							    } else {
								    $journal
									    .addClass('open')
									    .siblings('.journal')
									    .removeClass('open');
								    $div
									    .slideDown('slow')
									    .siblings('.journal-contents')
									    .slideUp('slow');
							    }
    								
							    $(this).blur();					
							    return false;
						    }); // eo: click + header
				    }); // eo: journals
		    }); // eo: journal
    	
		ais.prepJournalFirstClass();
	    //$('.journals > .journal:first').addClass('first');
	    //$('.journals > .journal:last').addClass('last');
    		
    }; // eo: .prepJournals

	ais.prepJournalFirstClass = function () {		
		$('.journals > .journal:first')
		    .addClass('first');
	    $('.journals > .journal:last')
		    .addClass('last');
	};
	
    ais.prepTabbedBox = function () {
    // requires ais.jsCSS
    /*
    assumes:
    .tabbed
	    .sliding-panel-frame
		    .sliding-panel-group
			    .sliding-panel
				    .tab
    */
	    // jQuery(expression, context)							
	    $('.tabbed')
		    .each(function () {
			    var $tabbed_box, $ul, sliding_panel_control_obj, sliding_panel_group, $sliding_panels, sliding_panel, sliding_panel_width, sliding_panel_margin;
    			$tabbed_box = $(this);
			    sliding_panel_margin = 0; //8;
			    $sliding_panels = $tabbed_box.find('.sliding-panel-frame > .sliding-panel-group > .sliding-panel');
    			
			    sliding_panel = $sliding_panels.get(0); // get dom element rather than jQuery object
    			
			    // resize Panel Group
			    sliding_panel_width = sliding_panel.offsetWidth + sliding_panel_margin;
			    sliding_panel_group = $('.sliding-panel-frame > .sliding-panel-group', $tabbed_box).get(0);// get dom element rather than jQuery object
			    sliding_panel_group.style.width = ($sliding_panels.length * sliding_panel_width) + "px";
			    sliding_panel_control_obj = { // function scoped for each .tabbed box
				    tab_index: 0,
				    selected_tab_index: 0,

				    // next properties used by: ais.slidePanelGroup
				    speed: 20, 
				    sliding_panel_group_el: sliding_panel_group,
				    timeout: 0
			    };
    	
			    $ul = $('<ul class="horizontal tabs"></ul>');
			    //$('.sliding-panel-frame > .sliding-panel-group > .sliding-panel')
			    $sliding_panels
				    .each(function (i) {
					    var $sliding_panel, $li, $a, tab_txt, target_x;
    					
					    $sliding_panel = $(this);
					    tab_txt = $sliding_panel
						    .find('.tab')
						    .eq(0) // only one .tab per .sliding-panel allowed
						    .text();
					    tab_txt = tab_txt ? tab_txt : "tab " + i;
					    target_x = 0 - (i * sliding_panel_width);
    					
					    // if tab hasClass .x [the black spot] then remove header
					    $sliding_panel
						    .find('.tab')
						    .each(function () {
							    $(this)
								    .filter('.x')
								    .remove();
						    });
    					
					    $li = $("<li></li>");
					    $a = $('<a href="#"></a>');
					    $a
						    .html(tab_txt)
						    .click(function () {
							    var $this = $(this);
    							
							    // search for journal-contents within sliding panel and hide if open
							    /* js journals removed
								$sliding_panel
								    .parent() // .sliding-panel-group
								    .find('.journals')
								    .children('.journal-contents')
								    .slideUp('fast')
								    .siblings('.journal')
								    .removeClass('open');
    							*/
								
								ais.slidePanelGroup(sliding_panel_control_obj, target_x);
							    $this
								    .parent() // LI
								    .addClass('this')
								    .siblings()
								    .removeClass('this');
    									
							    $this.blur();					
							    return false; // overide mouse event
						    });
					    $li.append($a);
					    $ul.append($li);
				    });	
			    $ul
				    .find('li:first')
				    .addClass('this');
			    $tabbed_box.prepend($ul);
		    });
    };

    ais.slidePanelGroup = function (sliding_panel_control, target_x) { // el gets animated
	    var el, x, repeat, adjust, denominator, timeout_function;
		denominator = 8;
	    repeat = true;
	    el = sliding_panel_control.sliding_panel_group_el;
	    if (sliding_panel_control.timeout) {
		    clearTimeout(sliding_panel_control.timeout);
	    }
	    if (!el.style.left) {
		    el.style.left = "0px";
	    }
	    x = parseInt(el.style.left, 10);
	    if (x < target_x) {
		    adjust = Math.ceil((target_x - x) / denominator);
		    x = x + adjust;
		    if (x > target_x) {
			    x = target_x;
		    }
	    }
	    if (x > target_x) {
		    adjust = Math.ceil((x - target_x) / denominator);
		    x = x - adjust;
		    if (x < target_x) {
			    x = target_x;
		    }
	    }
	    if (x === target_x) {
		    repeat = false;
	    }
	    el.style.left = x + "px";
	    if (repeat) {
		    timeout_function = function () {
			    ais.slidePanelGroup(sliding_panel_control, target_x);
		    };
		    sliding_panel_control.timeout = setTimeout(timeout_function, sliding_panel_control.speed);
	    } else {
		    if (sliding_panel_control.timeout) {
			    clearTimeout(sliding_panel_control.timeout);
		    }
	    }
    };

    ais.initAccordion = function () {
	    var page_str = ais.text.page + " ";
		var hide;
		
		hide = function () {
			// callback
			$(this)
				.addClass('closed')
				.removeAttr("style")
				;
		};
		
	    $('.leaf')
		    .each(function (i) {
			    var page_num, $leaf, $leaf_inner, $a, $span_open_close, $span_hover, leaf_title, $first_leaf_title;
			    page_num = i + 1;
    			
    			$leaf = $(this);
    			
				$first_leaf_title = $('.leaf-title:first', this);
				leaf_title = $first_leaf_title.text() || page_str + page_num;
				$first_leaf_title.remove();

			    $leaf
				    .wrapInner('<div class="leaf-inner"></div>');
    				
			    $leaf_inner = $leaf
				    .children('.leaf-inner')
				    .eq(0)
				    .hide()
					.addClass('closed')
					.removeAttr("style")
					;	
    			
			    $span_hover = $('<span></span>')
			        .text(leaf_title);
					//.text(page_str + page_num);
    				
			    $span_open_close = $('<span></span>')
				    .append($span_hover);
    			
			    $a = $('<a href="#"></a>');
			    $a
				    .addClass('leaf-toggle')
				    .click(function () {
					    if ($leaf_inner.is(':visible')) {
						    $leaf
							    .removeClass('leaf-open')
							    .children('.leaf-inner')
							    .slideUp('slow', hide)
								;		
					    } else {
						    $leaf
							    .addClass('leaf-open')
							    .children('.leaf-inner')
							    .slideDown('slow')					
								.removeClass('closed')
							    .end()
							    .siblings()
							    .removeClass('leaf-open')
							    .filter(':visible')
							    .children('.leaf-inner')
							    .slideUp('slow', hide)
								;
					    }
					    $a.blur();
					    return false;
				    })
				    .hover(
					    function () {
						    $span_hover.addClass("hover");
					    }, 
					    function () {
						    $span_hover.removeClass("hover");
					    })
				    .append($span_open_close)
					;			
			    $leaf.prepend($a);
		    });
		    $('.leaf:first')
			    .addClass("leaf-open")
				.children('.leaf-inner')
			    .show()
				.removeClass('closed')
				;
    };
	

    ais.addHrefSlideToggle = function (selector_str) {
        /*
        argument: jQuery selector string for an A link with an href.
        requires href to contain #fragment id of an element which will be toggled
        with a slide up / down.    
        */
        
        var href, $href;
        href = $(selector_str).attr("href");
        $href = $(href);
        $href.css({"display" : "none"});
        
        $(selector_str)
          .toggle(
                function () {
                    $href.slideDown();
                    $(this)
                        .toggleClass('open')
                        .blur();
				    return false;
                },
                function () {
                    $href.slideUp();
                    $(this)
                        .toggleClass('open')
                        .blur();
				    return false;
                }
            );
    };
    
    ais.prepLightbox = function () {
        if (typeof $().slimbox === 'function') {
            $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function (el) {
	            return (this === el) || ((this.rel.length > 8) && (this.rel === el.rel));
            });
        };   
    };
       
    ais.switcherPrefs = {
	    optionsId: "#switcher-options",
	    cssOptions: [
		    {title: "sci", name: "Default", cssClass: "default"},
		    {title: "alt", name: "Contrast"}
	    ],
	    cookieName: "css-switcher"
    };

    ais.text = {
	    backtotop: "back to top",
	    page: "Page"
    };

    ais.init = function () {
	    
	    if ($('#scWebEditRibbon').size() === 0) { // then you're not in sitecore edit mode
	        ais.jsCSS();
	        ais.prepLinkRels("Opens in new window");
	        ais.initSearch("#header-search-bar");
			// ais.prepJournals();
			ais.prepJournalFirstClass();
			
	        ais.prepTabbedBox();
	        ais.initAccordion();
	        ais.prepLightbox();
	    } else {
	    
	        $('body').addClass('webedit');
	    }
    };

    $(document).ready(function () {
	    ais.init();			
    }); // eo:ready

})(jQuery);
