/*Self Executing code*/
;(function() {

    //JQuery is not loaded already
    if (!jQuery) {
        return;
    }
    // JQuery Plugin Menu accordion is not loaded
    if (!ddaccordion) {
        return;
    }

    jQuery(document).ready(function () {
        //Try to grab the menu from the file mentioned thru AJAX
        //loadMenu();
		menuHook();
        var breadCrumb =  (TallyWebsite && TallyWebsite.Breadcrumb) || {};
        var breadCrumbContainer = (TallyWebsite && TallyWebsite.BreadcrumbContainer) || "breadCrumb";
        var prevLink = (TallyWebsite && TallyWebsite.PrevLink) || "prev";
        var nextLink = (TallyWebsite && TallyWebsite.NextLink) || "next";
        CreatePrevNextLink(prevLink, nextLink);
        CreateBreadCrumb(breadCrumb, breadCrumbContainer);
        $('.CrossLinks').bind('click', {index: 1}, CrossLinkParserOperations);
    	}
    );
})();
var LinkArr = Array();
function CrossLinkParserOperations( event )
{
	//get the href from  the anchor tags.
    var url = this.href;
    var className = this.className;
    //if not '#' then get the data
    if(url != "#") {
        $('.CrossLinks').unbind( "click" );
        LinkArr.push(url);
        if (event.data.index > 1)
            TallyWebsite.Breadcrumb.push( {title: $(".mainheading").text(), href: LinkArr[LinkArr.length-2], cssclass: "CrossLinks" });
        else
            TallyWebsite.Breadcrumb.push( {title: $(".mainheading").text(), href: window.location.href});

        //load the data.
        $("#body").load(url,"",function() {
            //change document title
            document.title = $(".mainheading").text();
            var breadCrumb = (TallyWebsite && TallyWebsite.Breadcrumb) || {};
            var breadCrumbContainer = (TallyWebsite && TallyWebsite.BreadcrumbContainer) || "breadCrumb";
            //remove all breadcrumb links
            //$(breadCrumbContainer).html('');
            var clickedIdX=0;
            if(className === "CrossLinks")
            {
                    for (idx in breadCrumb)
                    {
                        val = breadCrumb[idx];
                      if(val['href'] === url)
                      {
                          clickedIdX = idx;
                          break;
                      }
                   }
                   if(clickedIdX)
                   {
                       len = breadCrumb.length;
                       breadCrumb.splice(clickedIdX,len);
                   }
            }
            document.getElementById(breadCrumbContainer).innerHTML = '';
            CreateBreadCrumb(breadCrumb, breadCrumbContainer);
            //after the load the same function is called to set the click event for the anchors in the loaded part.
            $('.CrossLinks').bind('click', {index: 2 }, CrossLinkParserOperations);
			try {parent.resize_iframe(0);} catch(e){}
        });
    }

    //returning false to stop the href work.
    event.preventDefault();
    return false;
}

function CreateBreadCrumb(obj, histContainer) {

    //Nothing to traverse and create
    if (!obj || typeof obj !== "object" || obj.constructor !== Array || obj.length <= 0 || !obj[0].title) return;

    if ((histContainer = jQuery.trim(histContainer)) === "") return;

    //normalize the content of Object Array
    jQuery.each(obj, function (idx, val) {
        val['title']    = val['title'] ? jQuery.trim(val['title']) : "";
        val['href']     = val['href'] ? jQuery.trim(val['href']) : "";
    });
    
    var cont = jQuery("#"+histContainer),
        next = "";
    for (var i = 0, l = obj.length; i < l; i++) {

        if (obj[i].title === "") {
            continue;
        }
        if (obj[i].href)  {
            if (typeof obj[i].cssclass === 'undefined')
            cont.append(next+"<a href=\""+obj[i].href+"\">"+obj[i].title+"</a>");
			else 
            {
                cont.append(next+"<a class=\""+obj[i].cssclass+"\" href=\""+obj[i].href+"\" >"+obj[i].title+"</a>");
            }
        }
        else {
            cont.append(next+"<span>"+obj[i].title+"</span>");
        }
        
        next = "&nbsp;<b>&rsaquo;</b>&nbsp;";
    }
    cont.append(next +"<span>"+(document.title || "["+window.location.href+"]")+"</span>");
}
/*
Find the header index @ current menu level where the anchor containing filename is and expand.
->first try checking if leaf(content aread) has the url of page to be loaded
->second try if header has the matching URL
->else Do nothing
*/
function ExpandHeader(obj) 
{
	var hdrIdx = parseInt(obj.anchor.parents('.'+obj.config.contentclass).parent().children('.'+obj.config.headerclass).attr("headerindex"));
	if (!isNaN(hdrIdx)) {
		ddaccordion.expandone(obj.config.headerclass, hdrIdx);
	}else {
		hdrIdx = parseInt(obj.anchor.parents('.'+obj.config.headerclass).attr("headerindex"));
		if (!isNaN(hdrIdx)) {
			ddaccordion.expandone(obj.config.headerclass, hdrIdx);
			//alert('selected ' +obj.selectClass);
			if (obj.selectClass !== '') obj.anchor.addClass(obj.selectClass);
		}
	}
}
/**
 *  Once the menu html has been loaded, this func will hook the html content with accordion to bring the menu 
 * 
 */
function menuHook() {

    //Crude way to get the filename
    var loc         = window.location.href.split("/");
    var fName       = (TallyWebsite && jQuery.trim(TallyWebsite.CurrentFile)) || loc[loc.length-1],
        menuC       = (TallyWebsite && jQuery.trim(TallyWebsite.MenuContainer)) || "",
        selected    = (TallyWebsite && jQuery.trim(TallyWebsite.MenuSelectedClass)) || "",
        openClass   = (TallyWebsite && jQuery.trim(TallyWebsite.MenuHeaderOpenClass)) || "";

    if (!menuC) return;

    if (selected) {
        jQuery("#"+menuC+" a").removeClass(selected);
    }

    //store a ref to anchor element containing the filename, if any
    var anchorRef = jQuery("#"+menuC+" a[href$='"+fName+"']");

    //Each Init indicates one level of Menu
    //1st level
    ddaccordion.init(
    { headerclass:"accordHL1",contentclass:"accordCL1",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:true,persiststate:false,toggleclass:["",openClass],animatespeed:"fast"
        ,togglehtml:[]
        ,oninit:function(headers, expandedindices) {
            /*Menu Structure is roughly as -
            Please refer to one of the menu files for detailed structure/markup
            <div ..>
                <div>
                    <p class=accordHL1 ..><a>Heading</a></p>
                    <ul class=accordCL1 ..>
                        <li><a href=page.html target=... >Page name</a></li>
                        <li>
                            <p class=accordHL2 ..><a>Heading</a></p>
                            <ul class=accordCL2 ..>
                            <li><a>page 2</a></li>
                            ...
                            </ul>
                        </li>
                        ...
                    </ul>
                </div>
                ...
            </div>
            */
			ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
        }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );
    //2nd level
    ddaccordion.init(
    { headerclass:"accordHL2",contentclass:"accordCL2",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:"fast"
        ,oninit:function(headers, expandedindices) {
         ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
        }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );
    //3rd level
    ddaccordion.init(
    { headerclass:"accordHL3",contentclass:"accordCL3",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //4th level
    ddaccordion.init(
    { headerclass:"accordHL4",contentclass:"accordCL4",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //5th level
    ddaccordion.init(
    { headerclass:"accordHL5",contentclass:"accordCL5",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //6th level
    ddaccordion.init(
    { headerclass:"accordHL6",contentclass:"accordCL6",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //7th level
    ddaccordion.init(
    { headerclass:"accordHL7",contentclass:"accordCL7",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //8th level
    ddaccordion.init(
    { headerclass:"accordHL8",contentclass:"accordCL8",revealtype:"click",collapseprev:true,defaultexpanded:[],onemustopen:false,animatedefault:false,persiststate:false,toggleclass:["",openClass],togglehtml:["none","",""],animatespeed:""
    ,oninit:function(headers, expandedindices){ 
        ExpandHeader({ anchor: anchorRef, config: this, selectClass: selected});
    }, onopenclose:function(header, index, state, isuseractivated){ try {parent.resize_iframe(0);} catch(e){}}
    }
    );

    //Suppress click events on links which have nowhere to go
    jQuery("a[href=#]").click(function(event) {
        event && event.preventDefault();
    });
	
	if (selected) {
        anchorRef.addClass(selected);
    }
    //find all elem with menuheader class and which has some valid urls
	jQuery('.menuheader:has("a[href!=#]")').bind("click", {file: fName}, 
        function(e) {
			var t = jQuery(this); var x = t.children("a[href!=#]").eq(0); var y = jQuery.trim(x.attr('href'));
			if (y !== '' && y !== '#' && y != e.data.file) window.location.href = y;
			return false;
		}
		);
}

//Fetch Data using AJAX- note the file has to be in the same domain
function loadMenu(){

    var menuC   = (TallyWebsite && jQuery.trim(TallyWebsite.MenuContainer)) || "",
        menuF   = (TallyWebsite && jQuery.trim(TallyWebsite.MenuFile)) || "";

    if (menuC && menuF) {
        jQuery.ajax({ 
                   method: "get",url: menuF, 
                   beforeSend: function(){jQuery("#"+menuC).append("<div class='loading'>Loading...</div>");}, 
                   complete: function(){ jQuery("#"+menuC+" div.loading").remove();}, 
                   success: function(html){ 
                        //inject the html into the menu container 
                        jQuery("#"+menuC).append(html);
                        //activate menu behaviour on this
                        menuHook();
                        }
                });
    }
}

//Find the next link to be clicked while clicking next button
function CreatePrevNextLink(prevLink, nextLink)
{
    //selected or current link
    var currentSelected = $("div #menuAccordion .selected");
    //find all the anchors in the menu
    var yourAnchors = $("div #menuAccordion a[href]");
    //current link index in the group of ilink objects
    var index = yourAnchors.index( currentSelected );
    //var a = 0,text="",curr=0;
    //while ( a < yourAnchors.length )
    //{
    //    x = yourAnchors.eq( a );
    //    text = text + x.text();
    //    if(x.attr("class") == "selected")
    //    {
    //        curr = a;
    //    }
    //    a++;
    //}
    //alert(text);
    //alert(index);
    var nextElement = "";
    //loop through link cloud
   while ( index>-1 && index  < yourAnchors.length )
    {
                   //get object of the links
                   nextElement = yourAnchors.eq( index );
                   //get the href property of the links
                   var hrefEmpty = jQuery.trim(nextElement.attr("href"));
                   //case: check the anchor tag's href property is there or not
                   if( hrefEmpty == "" || hrefEmpty == "#" )
                   {
                       index ++;
                   }
                   else
                   {
                       //element found
                       index ++;
                       nextElement = yourAnchors.eq( index );
                       break;
                   }
    }

   var index = yourAnchors.index( currentSelected );
   var prevElement = "";
   if(index>=1)
   {
       var x=1;
       while(x<=index)
       {
           prevElement = yourAnchors.eq( index - x );
           var hEmpty = jQuery.trim(prevElement.attr("href"));
           if( hEmpty == "" || hEmpty == "#" )
           {
               x++;
           }
           else
           {
               x++;
               break;
           }
       }
   }
    
    var prevDiv = jQuery("[name=\""+prevLink+"\"]"), nextDiv = jQuery("[name=\""+nextLink+"\"]");
	
    if(prevElement!="")
    {
        $(".ArrowPrev").append("<a href=\""+prevElement.attr("href")+"\" title=\""+prevElement.text()+"\">&laquo;</a>");
		prevDiv.append("<span class=\"subheading\">&laquo;</span> <a  target=\""+prevElement.attr("target")+"\" href=\""+prevElement.attr("href")+"\">"+prevElement.text()+"</a>");
    }
    if(nextElement!="")
    {
        $(".ArrowNext").append("<a href=\""+nextElement.attr("href")+"\" title=\""+nextElement.text()+"\">&raquo;</a>");
        nextDiv.append("<a href=\""+nextElement.attr("href")+"\"   target=\""+nextElement.attr("target")+"\" >"+nextElement.text()+"</a> <span class=\"subheading\">&raquo;</span>");
    }
}


