var imageOpened = "&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;";
var imageClosed = "&nbsp;&nbsp;&nbsp;&raquo;&nbsp;&nbsp;&nbsp;";
var imageBack = '<a href="#">&nbsp;&laquo; Retour</a>';
var imageAjaxLoad = '&nbsp;&nbsp;&nbsp;<img src="http://test.performancenc.ca/templates/jscript/iPodTreeMenu/ajax-loader.gif" border="0" />&nbsp;&nbsp;';

var menuWidth = "225px"; //226
var iSubOffset = "15";
var iCurrentPage = 0;
var iDepths = new Array(0,0);
var menuPages = new Array("page0","page1"); 



function initMenu(menuID){
    $('#' + menuID + ' li[id!=menuBack] a').prepend('<span id="menuImage">' + imageClosed + '</span>');
    $('#' + menuID + ' ul>li>ul').hide(); //hide menu's 1st level;
    $('#' + menuID).css({width: menuWidth});  
    $('#' + menuID).addClass('iPodTree');      
    $('#' + menuID + ' li').bind('click', _handleMenuClick);
}

function exposePage(exposedPage){
    if (exposedPage){
        var exposeArray = exposedPage.split("/");
        var firstPageID = menuPages[iCurrentPage];
        $('#' + firstPageID).hide();
        var o = $('#'+firstPageID);
        for(var i=0; i < exposeArray.length; i++){
            var textToFind = exposeArray[i];
            var prevMenuID = menuPages[iCurrentPage];
            var o = _findli(o, textToFind);

            var oDepth = o.parentsUntil('#'+ prevMenuID).filter('ul'); 
            var iCurrentDepth = oDepth.length; 
            
            //var sHtml = o.find('ul').html();
            var sHtml = "<ul>" + o.find('ul').html() + "</ul>";
            var nextMenuID = _preparePage(sHtml,iCurrentDepth);
            $('#' + nextMenuID + ' li').bind('click', _handleMenuClick); 
            $    
            $('#' + nextMenuID).hide();
        }
         $('#' + nextMenuID).show();
        
    }
}

function _findli(oContext, textToFind){
    var o = "empty";
    oContext.find('li a:contains("'+textToFind+'")').each(  $.proxy(function(){
        var oTextNodesOnly = $(this).contents().filter(function() {
            return this.nodeType == 3;
            });
        var thisText = $(oTextNodesOnly).text();
        if(thisText==textToFind){
            o = $(this).closest('li');
            return false;
            }
    }));
    return o;
}

function _handleMenuClick(event){
    var o = $(this);
    var menuID = menuPages[iCurrentPage];
    var iDepth = o.parentsUntil('#'+ menuID).filter('ul').length; 
    /*if (iCurrentPage>0) //remove the count of the menuBack node (fix should be done in the previous line instead of this way)
        iDepth-=1; */
    var iGlobalDepth = sumArray(iDepths)+iDepth;
    if (o.is('#menuBack')){
        _pageBack(o);
    } else if (o.is('.AjaxPage') ){
        event.preventDefault(); //don't follow link
        var strAjaxURL = o.children('a').attr('href');
        var strRef = o.children('a').attr('rel');
        if (strAjaxURL!='#' && strAjaxURL!='')
            _openPageNode(o, iDepth, strAjaxURL, strRef);
    } else if (o.children('ul, li').is(':hidden')){ //Has hidden ul li childs   
        if (o.children('ul').is('.menuPage')  || myInArray(iGlobalDepth, autoPages) ){  //created a new function because IE doesn't support jQuery's $.inArray
            _openPageNode(o, iDepth);
        } else { 
            _openTreeNode(o, iDepth);
        }
    } else if (o.children('ul, li').is(':not(:hidden)')) { //Has visible childs 
        _closeTreeNode(o);
    } else { // if no hidden or visible childs, its a normal node item so don't do anything    
        return true; //do nothing
    }
    log("Menu:" + menuID + " Page:"+(iCurrentPage)+" GlobalDepth:" + iGlobalDepth + " CurrentDepth:" + iDepth);
    return false;
};


function _openTreeNode(o, iDepth){
    var iOffset = iSubOffset*iDepth;
    o.toggleClass('menuItemOpened', true); 
    o.children('ul').children('li').toggleClass('menuSubItems', true);
    //$(this).children('ul').eq(0).toggleClass('menuGroupOpened', true);
    o.find('#menuImage').eq(0).html(imageOpened);
    o.children('ul').children('li').children('a').children('#menuImage').css('padding-left', iOffset +'px');
    o.children('ul, li').show('slow');
    o.children('ul, li').css('font-weight', 'normal'); //to fix bold beeing always on
}    

function _closeTreeNode(o){
    o.toggleClass('menuItemOpened', false); 
    o.toggleClass('menuSubItems', false);
    o.find('#menuImage').eq(0).html(imageClosed);
    o.children('ul, li').hide('slow');
}

function _openPageNode(o, iCurrentDepth, AjaxURL, AjaxRef){
    var prevMenuID = menuPages[iCurrentPage];
    if (!AjaxURL) {
        var sHtml = "<ul>" + o.find('ul').html() + "</ul>";
        //sHtml = "<ul>" + sHtml + "</ul>";   //log(sHtml);
        var nextMenuID = _preparePage(sHtml,iCurrentDepth);
        $('#' + nextMenuID + ' li').bind('click', _handleMenuClick);            
    } else {
       
        var sHtml = $.ajax({
          type: "GET",
          url: AjaxURL+"ajaxCall_"+AjaxRef+"/",
          async: false,
          beforeSend: function(data) {
            //o.addClass('ajaxClicked');
                o.find('#menuImage').eq(0).html(imageAjaxLoad);
                //obj.find('a').css({cursor:'wait'});
          },
          complete: function(data) {
                //$('body').css({cursor:'auto'});
                o.find('#menuImage').eq(0).html(imageClosed);
                //o.removeClass('ajaxClicked');
          }
         }).responseText;
        
        //log(sHtml);

        var nextMenuID = _preparePage(sHtml,iCurrentDepth);
        initMenu(nextMenuID);
    }
    _animateMenu(prevMenuID, nextMenuID, "next");
}

function _preparePage(sHtml, iCurrentDepth){
    iDepths[iCurrentPage] = iCurrentDepth;
    var prevMenuID = menuPages[iCurrentPage];
    iCurrentPage+=1;
    var nextMenuID = "page"+(iCurrentPage); 
    menuPages[iCurrentPage] =  nextMenuID;
    $('#' + nextMenuID).remove(); //we want only one copy of each page        
    $('#' + prevMenuID).after('<div id="'+ nextMenuID +'"></div>');
    $('#' + nextMenuID).html('<ul><li id="menuBack">'+ imageBack +'</li></ul>' + sHtml);
    $('#' + nextMenuID).css({width: menuWidth});
    $('#' + nextMenuID).addClass('iPodTree');
    
return nextMenuID;
}

function _animateMenu(prevMenuID, nextMenuID, sDirection){
    //Animate!
    switch(sDirection){
        case "next":
            
            //$('#' + nextMenuID).css({position:'absolute'});
            //var prevOffset = $('#' + prevMenuID).offset();
            //var currOffset = $('#' + nextMenuID).offset();
            //prevOffset.left+=$('#' + prevMenuID).outerWidth();
            //$('#' + nextMenuID).css({'z-index':'999'});
            //$('#' + nextMenuID).offset({top:0, left:0});
            //{top:prevOffset.top, left:prevOffset.left}
            //$('#iPodTreeMenu').height($('#iPodTreeMenu').height());
            var nextHeight = $('#' + nextMenuID).height();
            $('#iPodTreeMenu').animate({height:nextHeight});
            var prevOffset = $('#' + prevMenuID).offset();
            $('#' + nextMenuID).offset(prevOffset);
            $('#' + prevMenuID).hide('slide',{direction: 'left'});
            //$('#' + nextMenuID).show('slide',{direction: 'right'});
            $('#' + nextMenuID).show('slide',{direction: 'right'}, function() {
                $('#' + nextMenuID).offset(prevOffset); //force to fix a weird bug
                $('#iPodTreeMenu').css({height:''});
              });
            
        break;
        case "back":
            //var tempOffset = $('#' + nextMenuID).offsetParent().offset();
            //$('#' + prevMenuID).css({top:tempOffset.top, left:tempOffset.left});
            //offset(tempOffset);
            var nextHeight = $('#' + nextMenuID).height();
            $('#iPodTreeMenu').animate({height:nextHeight});
            $('#' + prevMenuID).hide('slide',{direction: 'right'});
            $('#' + nextMenuID).show('slide',{direction: 'left'}, function() {
                $('#iPodTreeMenu').css({height:''});
                //$('#' + nextMenuID).offset(prevOffset);
              });
        break;

        default:
    }
}

function _pageBack(o){
    var prevMenuID = menuPages[iCurrentPage];
    iCurrentPage-=1;
    var nextMenuID = menuPages[iCurrentPage];
    iDepths[iCurrentPage] = 0; //Reset the previous page's depth since we are not in its subs anymore
    _animateMenu(prevMenuID, nextMenuID, "back");
}        
    
function myInArray(needle, haystack) { 
    var length = haystack.length
    for(var i = 0; i < length; i++) { 
        if(haystack[i] == needle) return true; 
    } 
    return false; 
} 

function sumArray(arr) {
    var iSum = 0;
    for(var i = 0; i < arr.length; i++) { 
        iSum += arr[i];
    } 
    return iSum; 
}

function log() {
    if (window.console && window.console.log)
        window.console.log(Array.prototype.join.call(arguments,' '));
};

$.fn.outerHtml = function(){
    if (this.length){
        var div = $('<div style="display:none"></div>');
        var clone = $(this[0].cloneNode(false)).html(this.html()).appendTo(div);
        var outer = div.html();
        div.remove();
        return outer;
    } else
    return null;
};    
