/*
 *    OPSI - ACT/EN-Interweave. 
 *    =========================
 *
 *    TODO: Add trace and debug code for deployment...
 */


/*
Change history
9999094430
Date                    Version            Name                        Description
======================================================
20/03/2009			0.1				MP					Control added for global show/hide							
20/03/2009			0.2				MP					Control added for really global (not per act as above  0.1) show/hide							
24/03/2009			0.3				MP					State management for show/hide act/local buttons/cookies!!!	
30/03/2009          	0.4             	MP                       Fix for weird interaction between local global show hide
01/04/2009          	0.5             	MP                       Gloabl show hide - button demo - moved to next page - needs a div on accessability called __ENExpandExplanatory to work    
03/04/2009          	0.6             	MP                       Global cookies don't expire at end of session     
23/04/2009			0.7			 	MP					Fix for inital press of act show/hide does not show/hide when executed after a site site wide show/hide all
23/04/2009			0.8		 		MP				      New rules for attaching button and content depending on what kind of link it is.  ie an act/schedule or NI link and more control odf mormattintg
02/06/2009			0.9 			MP					New target points for fragments coded in. Some fragments point to strutures other than what was evnisaged
03/06/2009			0.10 			MP					Fixes for positioning schedule part buttons...
19/08/2009			0.11			PG					Set EN_FRAG_LOC conditionally depending on legislation type: em for uksi, en for others
04/09/2009			0.12			PG				Updated  "showENFragment", function() to allow for an outer wrapped div on the ENFragment divs
12/10/2009          0.13            CM              Removed styles on the elements, changes to use css file.
13/10/2009          0.14            VS              Changes for not to use space on the page when act show/hide button is not in use.

*/



/*
 *    Some global parameters
 */
var SEP_CHAR="/"; 
// var EN_FRAG_LOC="en"+SEP_CHAR;
var ENABLE_DEBUG_WITH_FIREBUG_CONSOLE = false;    /*    set this to false on deply*/
var ACT = "";
var SHOWSTATE = { 
    global: null,
    local: null
};


/*
 *    This is for dynmaically loading the css
 */
$(document).ready(function() {
        var head = $(document).find("head");
        head.append("<link rel='stylesheet' href='/styles/explanatoryNotesInterweave.css' type='text/css'/>");
        __debuglog("dynamic stylesheet added");        
    }               
 );



/*
 *    The link register is examined and eligible links are retrieved.
 *    Retrieval is predicated on by this file's name being equal to a
 *    key called "legislation-fragment" in the register.
 */
$(document).ready(function() {
       EN_FRAG_LOC = "en"+SEP_CHAR;
        var __debug_count = 0;
        var page = fileBase();
        if ( page.indexOf("uksi_") != -1 ) {
        	EN_FRAG_LOC="em"+SEP_CHAR;
        } 
        ACT = page.substring(0, page.search('_en')+3);
        var interweave_links_loc=EN_FRAG_LOC+ACT+"_interweave_links.xml";
        SHOWSTATE.global = $.cookies.get("eniw"); 
        SHOWSTATE.local = $.cookies.get(ACT);           
          
        /*   ajax get callback gets link register */
        $.get(interweave_links_loc, function(data) {  
            __debuglog("this file:"+page+" lookup:"+interweave_links_loc);
            var g_eligibleLinks = $(data).find("link[legislation-fragment='"+page+"']");
            var g_eligibleLinks_no_null_id = g_eligibleLinks.filter("[id !="+''+"]"); 
            prepareUI(g_eligibleLinks_no_null_id);
            $("#__act_sabaidiimai").trigger("showMe");
        });
        __debuglog("link register processed:"); 
    }               
 );



/*
 *    This call will add the GLOBAL show/hide  
 */
$(document).ready(function() {
   
	var jUIElement = $("<div id='__ENExpandExplanatory'></div>");
    var uiCollapseText = "Collapse All Explanatory Notes (ENs)";
    var uiExpandText = "Expand All Explanatory Notes (ENs)"; 
    var uiText = uiExpandText;	  
  
    jUIElement.addClass("noteLink");  
    jUIElement.addClass("bigNoteLink"); 
    jUIElement.css("float", "none");

	if( SHOWSTATE.global == "collapsed") 
	    { uiText = uiExpandText;} 
	else if(SHOWSTATE.global == "expanded") 
	    { uiText = uiCollapseText; }
	jUIElement.text(uiText);

    jUIElement.click(function(event) {
        //SHOWSTATE.local = $.cookies.get(ACT);
        if(SHOWSTATE.global == "collapsed" || SHOWSTATE.global == null) {  
            jUIElement.text(uiCollapseText);
            $.cookies.set("eniw", "expanded", {
                hoursToLive: 87600
            });  
            SHOWSTATE.global = "expanded";  
        } else {
            jUIElement.text(uiExpandText); 
            $.cookies.set("eniw", "collapsed");
            SHOWSTATE.global = "collapsed"; 
        }       
    });

    //jUIElement.css("display", "inline");
    var hookENExpandExplanatory = $("#ENExpandExplanatory");
    hookENExpandExplanatory.append(jUIElement);
    hookENExpandExplanatory.append("<div>&nbsp;</div>");
});


/*
 *    This call will add the ACT show/hide
 */
$(document).ready(function() {

    var jUIElement = $("<div id='__act_sabaidiimai'></div>");
    var uiCollapseText = "Collapse All Explanatory Notes (ENs)";
    var uiExpandText = "Expand All Explanatory Notes (ENs)"; 
    var uiText = uiExpandText;

    jUIElement.css("display", "none");  
    //called when link register for this document is successfully processed
    jUIElement.bind("showMe", function() {
        $(this).addClass("noteLink");
        $(this).addClass("bigNoteLink");
        $(this).css("margin-bottom", "0.5em");
        $(this).css("display", "block");
        $(this).trigger("addSpacer"); 
    });
  
    // synchronise text of button with state  
    jUIElement.bind( "updateText", function() {         
        if(SHOWSTATE.local == null) {
        	if( SHOWSTATE.global == "collapsed" ) {
        	    uiText = uiExpandText;
        	} else if(SHOWSTATE.global == "expanded" ) {
        	    uiText = uiCollapseText;
        	} 
        } else {
            if( SHOWSTATE.local == "collapsed" ) {
                uiText = uiExpandText;
            } else if(SHOWSTATE.local == "expanded" ) {
                uiText = uiCollapseText;
            }         	
        }    
        jUIElement.text(uiText);
    });    
    jUIElement.trigger("updateText"); 
    
    // has effect of pressing all the show/hide buttons
    jUIElement.click(function(event) {
        __debuglog("in click:"+SHOWSTATE.local);
	  
	    if (SHOWSTATE.local == null) {
	 		if(SHOWSTATE.global == "collapsed" || SHOWSTATE.global == null) {
		            $("a.noteLink").trigger({
		                type:"click",
		                message:"show"
		            }); 
		            jUIElement.text(uiCollapseText);
		            $.cookies.set(ACT, "expanded");  
		            SHOWSTATE.local = "expanded"	 			
	 		} else {
		            $("a.noteLink").trigger({
		                type:"click",
		                message:"hide"
		             });
		            jUIElement.text(uiExpandText);
		            $.cookies.set(ACT, "collapsed");
		            SHOWSTATE.local = "collapsed"	 		
	 		}
         } else if(SHOWSTATE.local == "collapsed") {
            $("a.noteLink").trigger({
                type:"click",
                message:"show"
            }); 
            jUIElement.text(uiCollapseText);
            $.cookies.set(ACT, "expanded");  
            SHOWSTATE.local = "expanded"
        } else {
            $("a.noteLink").trigger({
                type:"click",
                message:"hide"
             });
            jUIElement.text(uiExpandText);
            $.cookies.set(ACT, "collapsed");
            SHOWSTATE.local = "collapsed"
        }
         __debuglog("bang done:"+SHOWSTATE.local);
    });

    $(".LegContent").prepend(jUIElement);
    
    // Adds a spacer div below show/hide button
    jUIElement.bind("addSpacer", function() {
        var nextElement = $(this).next("*")[0];
        if(nextElement != null) {
            var next = nextElement.tagName.toLowerCase();
            if("h3" == next || "h4" == next || "h5" == next || "p" == next || "div" == next ) {
                var spacer = $("<"+"div"+">"+"&nbsp;"+"</"+"div"+">");
                spacer.addClass("LegClearFix");
                spacer.addClass("LegP1ContainerFirst");
                $(this).after(spacer);  
            }
        }
    });

	__debuglog("act show/hide trigger added - (cookie SHOWSTATE.local:"+SHOWSTATE.local+")"); 
	
 });



/*
 * Get the base name of the file (this is name without '.htm/.html suffix)
 */
function fileBase() {

    var path = window.location.pathname;
    var page_html = path.substring(path.lastIndexOf(SEP_CHAR)+1);
    var page = page_html.substring(0, page_html.search('.htm'));
    if (page) {
		return page;	
	}else {
		return page_html;
	}
}



/*
 *    Show/Hide Explanatory Notes when element clicked  
 *
 *    The toggle event is bound to jUIElement - an ankor/button etc...
 *    The new content (identified by enFragmentResource) is retrieved and attached or removed from the document.
 *
 *    The JavaScript assumes a pattern something like this, where hx is some level of heading. 
 

 *   My script then joins on the id of the span and appends the link to the contents of the parent (head),
 *   and in rendering it floats right
 *
 */
 function attacheEN() {
 	
 }
 
function prepareENToggleEvent(pageTarget, enFragmentResource) {

    var jUIElement = $("<a>Show EN</a>");
    var targetType = pageTarget[0].nodeName.toLowerCase();
    

	var jHElement = null;
             
	/*Different documents have differnt structures...*/   
	
	/*Assumes a */
	
	if("span" == targetType) {	
	
		 /*       <hx>
		 *           <span id="id-to-join-on">23</span>
		 *           <span>Title Text</span>
		 *       </hx>
		 */	
		jHElement = pageTarget.parent();	
		jHElement.append(jUIElement);
		var parent = pageTarget.parent();
		var followingSpan = pageTarget.next("span");
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");
		//jUIElement.addClass("en_debug");
		followingSpan.removeClass("LegP1GroupTitleFirst");
		followingSpan.removeClass("LegP1GroupTitle");
		followingSpan.addClass("en_LegP1GroupTitle"); 
		
	} else if("div" == targetType) {
		if(pageTarget.next().get(0).nodeName.toLowerCase() != "p") {
			// some types of Schedule parts use this...
			jHElement = pageTarget.next();
		} else {
			jHElement = pageTarget.next().next();				
		}
		jHElement.append(jUIElement);
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");		
		
	} else if("a" == targetType) {
		// found in some scottish acts -
		// assumes there is a previous h element and appends button to that... (what ever it is)
		// asp_20020005_en_6 is an example
		jHElement = pageTarget.prev();
		jHElement.append(jUIElement);
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");

	}else if("p" == targetType) {
		// I think beginning of schedules can have these
		if ( pageTarget.attr("class").indexOf("LegSP1Container") != -1 ) {
			jHElement = pageTarget.prev();
		} else {
			jHElement = pageTarget.next();
		}
		jHElement.append(jUIElement);
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");

	} else if("h2" == targetType || "h3" == targetType || "h4" == targetType || "h5" == targetType) {
		// ofter NI types
		jHElement = pageTarget;
		jHElement.append(jUIElement);
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");

	} else {
	
		jHElement = pageTarget.parent();	
		jHElement.append(jUIElement);
		var parent = pageTarget.parent();
		var followingSpan = pageTarget.next("span");
		jUIElement.addClass("LegDS");
		jUIElement.addClass("noteLink");
		jUIElement.addClass("en_debug");
		followingSpan.removeClass("LegP1GroupTitleFirst");
		followingSpan.removeClass("LegP1GroupTitle");
		followingSpan.addClass("en_LegP1GroupTitle"); 
	}
    	jUIElement.attr("title", pageTarget.get(0).id);   /*    this line is for debugging    */

    // ..to here.
    
    var jEnId = false;	
    
    /*    bind a show event to the link    */
    jUIElement.bind( "showENFragment", function() {
        if(jEnId == false) {
            $.get(EN_FRAG_LOC+enFragmentResource, function(ENContent) {
            
            	// the tid attribute will either be on the top-level ENFragment div, 
            	// or on an inner ENFragment div if the fragment contains more than one ENFragment
                var idElement = $(ENContent).find("div[tid]");
                
                var tid = $(ENContent).attr("tid");
                
                if (typeof tid == "undefined")
                	tid = idElement.attr("tid");
                	
                jEnId = "__eniw_" + tid;
                
                var wrapper = $("<div class='eniw'></div>");
                wrapper.append(ENContent);
                wrapper.attr("id", jEnId);

                if("span" == targetType) { 
                
                		jHElement.after(wrapper);
                		
                } else if("div" == targetType) {
                
                		jHElement.after(wrapper);
				$(wrapper).css("margin-top", "30px");

                } else if("p" == targetType || "a" == targetType) {
                
                		jHElement.after(wrapper);
                		$(wrapper).css("margin-top", "30px");
                		
                } else if("h2" == targetType || "h3" == targetType || "h4" == targetType || "h5" == targetType) {
				// ofter NI types
                		jHElement.after(wrapper);
                		$(wrapper).css("margin-top", "30px");

		     }else {
		     
                		jHElement.after(wrapper);
                }
                jUIElement.text("Hide EN"); 
            });  
        }
    });
    
    /*    bind a hide event to the link    */
    jUIElement.bind( "hideENFragment", function() { 
        if(jEnId != false) {
            var elementToRemove = $("body").find("div#"+jEnId);
            elementToRemove.remove();
            jUIElement.text("Show EN");
            jEnId = false; 
         }   
    });
    
    /* 
     * Bind an onclick event - which triggres show and hide events
     * This may be triggered from the global show/hide components
     */
    jUIElement.click(function(event) {
        if(event.message == "show") {
            jUIElement.trigger("showENFragment"); 
        } else if (event.message == "hide") {
            jUIElement.trigger("hideENFragment");   
        } else {
            /*    default behaviour    */
            if(jEnId) {
                jUIElement.trigger("hideENFragment");    
            } else {
                jUIElement.trigger("showENFragment"); 
            }  
        }
    }); 
    
    prepareStateFromCookie(jUIElement);
}




/*
 *    Check cookie state - and display or hide
 *    Note this is ressurecting state from cookies so expanded -> show
 */
function prepareStateFromCookie(jUIElement) {
    
    if(SHOWSTATE.local == null) {
        //__debuglog("show all check global:"+SHOWSTATE.global);
        if( SHOWSTATE.global == "expanded") { 
            jUIElement.trigger("showENFragment"); 
        } else if( SHOWSTATE.global == "collapsed")  {
            jUIElement.trigger("hideENFragment");   
        }        
    } else {
        //__debuglog("show all check local:"+SHOWSTATE.local);
        if(SHOWSTATE.local == "expanded" ) { 
            jUIElement.trigger("showENFragment"); 
        } else if(SHOWSTATE.local == "collapsed")  {
            jUIElement.trigger("hideENFragment");   
        }    
    }        
}



/*
 *    A list of link elements that are eligible for this html fragment are processed.   
 *    For each eligible link a function is called which creates the jUIElement element and its event bindings...
 *     
 *    The target should be the first span that displays the clause number out the number
 */
function prepareUI(eligibleLinks) {
    var __debug_count = 0;
    eligibleLinks.each(     
        function(intKdex) {  
            var currentLink = $(this);
            var id = "#"+currentLink.attr("id");
            var enFragmentResource = currentLink.attr("en-fragment");
            var target = $(id); 
            prepareENToggleEvent(target, enFragmentResource); 
            __debug_count++;
    });
    return __debug_count;
}
 
/*    ======================    DEBUG FUNCTION    ======================    */ 

/*
 *
 *    Debug function
 *    if you are not using firefox change to alert or whatever
 *    and if you are not debigging commment out 
 */
function __debuglog(message) {

    if(ENABLE_DEBUG_WITH_FIREBUG_CONSOLE) {
        if($.browser.mozilla) {
             console.log(message);
         } else {
             
         }
     }
}




