﻿
//$jq = jQuery.noConflict();
var $jq = jQuery.noConflict();

$jq(function() {
//$jq(document).ready(function($jq) {

    /**************************************************************************************
    Martin H:  Start:  Modified section
    **************************************************************************************/
    //$jq('div.tabbed').tabs();   ///// this is the old outcommented definition of the tabset, needed to get the original code to run

    m2SetActivePageToCookie('activePageId', $jq('#HiddenPageId').val());
    //alert('Tabs:  set active page id cookie ' + $jq('#HiddenPageId').val());

    var pageId;
    pageId = m2GetActivePageFromCookie();

    var selectedTab;
    selectedTab = m2GetSelectedTabFromCookie(); //get unique tabindex for page

    $jq('div.tabbed').tabs({ selected: selectedTab });

    $jq('div.tabbed').bind('tabsselect', function(event, ui) {

        var pageId2;
        pageId2 = m2GetActivePageFromCookie();
        m2SetSelectedTabToCookie('selectedTabIndex' + pageId2, ui.index);

        //alert('now setting tabindex: selectedTabIndex p2 #' + pageId2 + '# p1 #' + pageId + '#');

        // Tab and Tab Listing Collapse/Expand Persistence:  This handles the case if this tab not the first tab opened
        var openCatArray = new Array();
        openCatArray = m2GetCatArrayFromCookie();
        
        // Marcia:  This was causing Sitecore Preview 'unterminated string' issue as it was returning a function{ instead of the id
        //var x;
        //for (x in openCatArray) {
        for (var x = 0; x < openCatArray.length; x++) {
            if (openCatArray[x] != 'SJM') {
                // Async calls getting out of sync with wrong openCatArray[x], so building the string and then executing;
                var jsStr = '';
                jsStr =
                "$jq('#" + openCatArray[x] + " .content').load(" +
                "	$jq('#a" + openCatArray[x] + "').attr('href')," +
			    "	function() {" +
			    "   $jq('#" + openCatArray[x] + " .content').css('display', 'block'); " +
			    "	    $jq('#" + openCatArray[x] + " .ctrl a').append('<img class=\"loader\" alt=\"loading\" src=\"" + uri_imgpath + "ajax-loader.gif\" />');" +
			    "	    $jq('#" + openCatArray[x] + "').slideDown(" +
			    "			animspeed," +
			    "			function() {" +
                "			    $jq('#" + openCatArray[x] + "').removeClass('closed').removeClass('not-loaded').addClass('opened').addClass('loaded');" +
			    "			    $jq('#" + openCatArray[x] + " img.loader').remove();" +
			    "			}" +
			    "		);" +
			    "	}" +
                ");";

                //alert('jsStr ' + jsStr);
                eval(jsStr);
            }
        };

    });
    /**************************************************************************************
    Martin H:  End: Modified section
    **************************************************************************************/

    $jq('ul.tabs>li a').livequery(
    	    'focus',
    	    function() {
    	        this.blur();
    	    }
        );

    $jq('div.ui-tabs-panel').addClass('clearfix');
    $jq('div.tabbed').each(function() {
        var local = $jq(this);
        var labels = Array();
        $jq('ul.tabs>li:not(".label")', this).each(function() {
            labels.push($jq(this).text());
        });
        for (var ii = 0; ii < labels.length; ii++) {
            $jq('.ui-tabs-panel:eq(' + ii + ')', local).prepend('<h3 class="tablabel">' + labels[ii] + '<\/h3>');
        }
    });


    // expand/collapse containers
    // .not-loaded can only be opened:
    //$jq('ul.ep-col li.not-loaded .ctrl a').click(
    //$jq('ul.exp-col li.not-loaded .ctrl a').livequery(
    // Marcia:  Used live instead of livequery because of an issue with having to click twice to collapse if opened by cookied
    $jq('ul.exp-col li.not-loaded .ctrl a').live(
        'click',
		function(x) {
		    //alert('not loaded click #' + $jq(this).attr('id'));

		    var link = $jq(this)
		    var local = $jq(this).parents('li');
		    $jq('.ctrl a', local).append('<img class="loader" alt="loading" src="' + uri_imgpath + 'ajax-loader.gif" />');
		    $jq('.content', local).load(
				$jq(link).attr('href'),
				function() {
				    $jq('.content', local).slideDown(
						animspeed,
						function() {
						    $jq(local).removeClass('closed').removeClass('not-loaded').addClass('opened').addClass('loaded');
						    $jq('img.loader', local).remove();

						    /**************************************************************************************
						    Martin H: Start: Modified section
						    **************************************************************************************/
						    var categoryId = $jq(local).attr('id');
						    m2AddCatValueToCookieArray(categoryId);  ///// within the function add the activePageId to the value
						    /**************************************************************************************
						    Martin H: End: Modified section
						    **************************************************************************************/
						}
					);
				}
			);
		    return false;
		}
	);

    // loaded items may expand or collapse

    //$jq('ul.exp-col li.loaded .ctrl a').click(
    //$jq('ul.exp-col li.loaded .ctrl a').livequery(
    // Marcia:  Used live instead of livequery because of an issue with having to click twice to collapse if opened by cookied
    $jq('ul.exp-col li.loaded .ctrl a').live(
		'click',
		function() {
		    //alert('loaded click');
		    var local = $jq(this).parents('li');
		    if ($jq(local).hasClass('opened')) { // close this		        
		        $jq('.content', local).slideUp(
					animspeed,
					function() {
					    $jq(local).removeClass('opened').addClass('closed');


					    /**************************************************************************************
					    Martin H: Start: Modified section
					    **************************************************************************************/
					    var categoryId = $jq(local).attr('id');
					    m2RemoveCatValueFromCookieArray(categoryId);
					    /**************************************************************************************
					    Martin H: End: Modified section
					    **************************************************************************************/

					}
				);
		    } else {
		        $jq('.content', local).slideDown(
					animspeed,
					function() {
					    $jq(local).removeClass('closed').addClass('opened');

					    /**************************************************************************************
					    Martin H: Start: Modified section
					    **************************************************************************************/
					    var categoryId = $jq(this).parents('li').attr('id');
					    m2AddCatValueToCookieArray(categoryId);
					    /**************************************************************************************
					    Martin H: End: Modified section
					    **************************************************************************************/
					}
				);
		    }
		    return false;
		}
	);

    $jq('a.expand').livequery(
		'click',
		function() {
		    $jq('li.closed .ctrl a').each(function() {
		        $jq(this).trigger('click');
		    });
		    return false;
		}
	);
    $jq('a.collapse').livequery(
		'click',
		function() {
		    $jq('li.opened .ctrl a').each(function() {
		        $jq(this).trigger('click');
		    });
		    return false;
		}
	);
});

/**************************************************************************************
Martin H: Start: New Functions for tab persistence
**************************************************************************************/

//***********************************************************************
/////
///// SECTION HANDLING category array in a cookie
/////


///// helpfunction - parses the array in a cookie to remove element by name from it
function m2RemoveElementInArray(arrayName, arrayElement) {
    //var strTmp; ////// remove
    for (var i = 0; i < arrayName.length; i++) {
        if (arrayName[i] == arrayElement) {
            arrayName.splice(i, 1);
        }
    }
    //alert('arrayelement: '+arrayElement);
    return arrayName;
}


///// helpfunction - detects if elements is in array or not.
function m2IsElementInArray(arrayName, arrayElement) {
    for (var i = 0; i < arrayName.length; i++) {
        if (arrayName[i] == arrayElement) {
            return true;
        }
    }
    return false;
}

///// returns array of a cookie
function m2GetCatArrayFromCookie() {
    var cookieArray = new Array();
    //alert('m2GetCatArrayFromCookie');
    try {
        
        var activePageId;
        activePageId = m2GetActivePageFromCookie(); // to get right tabindex

        //alert('GetCatArray '+activePageId);
        
        var selectedTab;
        selectedTab = m2GetSelectedTabFromCookie(); // identified by pageId aswell

        var inputCookieName;
        //alert('about to open cookie: ' + 'openCatIds'+activePageId+'tab'+selectedTab); ///// TESTING

        inputCookieName = 'openCatIds' + activePageId + 'tab' + selectedTab   // added with activePageId and selected tab indicator =
        // one cookie instance created for each tab

        ///// adds a cookie to the browser if it does´nt exist one
        if ($jq.cookie(inputCookieName) == null) {
            $jq.cookie(inputCookieName, "SJM", { path: '/', expires: 365 });
        }

        //alert('cookie found '+inputCookieName+' GetCatArray ' + activePageId + ' tab ' + selectedTab); 

        var cookieString;
        cookieString = $jq.cookie(inputCookieName);
        
        //alert('cookieString ' + cookieString);

        cookieArray = cookieString.split(",");
    }
    catch (Error) {
    }
    return cookieArray;

}

///// add a value to an category array in a cookie.
function m2AddCatValueToCookieArray(inputCatId) {
    try
    {
        //alert('AddCatValue' + inputCatId);
        
        var activePageId;
        activePageId = m2GetActivePageFromCookie(); // to get right tabindex

        var selectedTab;
        selectedTab = m2GetSelectedTabFromCookie(); // identified by pageId aswell

        var inputCookieName;
        inputCookieName = 'openCatIds' + activePageId + 'tab' + selectedTab   // added with activePageId and selected tab indicator =
        
        // one cookie instance created for each tab
        //alert('add category ' + inputCookieName + ' inputCatId');
        
        if ($jq.cookie(inputCookieName) == null) {
            $jq.cookie(inputCookieName, "SJM", { path: '/', expires: 365 });
        }

        var cookieString;
        cookieString = $jq.cookie(inputCookieName);

        var cookieArray = new Array();
        cookieArray = cookieString.split(",");

        if (!m2IsElementInArray(cookieArray, inputCatId)) {
            cookieArray.push(inputCatId);
            $jq.cookie(inputCookieName, cookieArray, { path: '/', expires: 365 });
        }
    }
    catch(err)
    {
    }
}

///// remove a value to an category array in a cookie.

function m2RemoveCatValueFromCookieArray(inputCatId) {
    try
    {
        var activePageId;
        activePageId = m2GetActivePageFromCookie(); // to get right tabindex

        var selectedTab;
        selectedTab = m2GetSelectedTabFromCookie(); // identified by pageId aswell

        var inputCookieName;
        inputCookieName = 'openCatIds' + activePageId + 'tab' + selectedTab   // added with activePageId and selected tab indicator =
        // one cookie instance created for each tab

        var cookieString;
        ///// get the string representing the array from the cookie
        cookieString = $jq.cookie(inputCookieName);

        var cookieArray = new Array();
        ///// spliting the arraystring to working array
        cookieArray = cookieString.split(",");

        if (m2IsElementInArray(cookieArray, inputCatId)) {
            ///// removes element from array
            cookieArray = m2RemoveElementInArray(cookieArray, inputCatId);

            //alert('Removing id ' + inputCatId);
            
            ///// adding the remaining array back to cookie
            $jq.cookie(inputCookieName, cookieArray, { path: '/', expires: 365 });
        }
    }
    catch(err)
    {
    }
}
/////
///// /END SECTION
/////



//***********************************************************************
/////
///// SECTION HANDLING tabIndex
/////

function m2SetSelectedTabToCookie(inputCookieName, inputValue) {
    $jq.cookie(inputCookieName, inputValue, { path: '/', expires: 365 });
}


///// check if needet to update this with pageId of if it is enough to just use the inputcookieName 
function m2GetSelectedTabFromCookie() {
    var selectedTab;
    selectedTab = 0;
    try
    {
        var activePageId;
        activePageId = m2GetActivePageFromCookie();   ///// might need to do a null check here before using the value
        ///// alert('getSelTabFrC - activePageId: '+activePageId);
   
        if ($jq.cookie('selectedTabIndex' + activePageId) == null) {
            $jq.cookie('selectedTabIndex' + activePageId, "0", { path: '/', expires: 365 });
        }
        else {
            selectedTab = $jq.cookie('selectedTabIndex' + activePageId);
        }
    }
    catch(Error)
    {
    }
    return selectedTab;
}

/////
///// /END SECTION
/////



//***********************************************************************
/////
///// SECTION HANDLING activePageId (in cookie) AND pageId (in page code)
/////


///// returns pageId if set to cookie
function m2GetActivePageFromCookie() {
    //    var pageId;
    if ($jq.cookie('activePageId') != null) {
        pageId = $jq.cookie('activePageId');
        return pageId;
    }
}


///// sets active pageId to the cookie variable overwrites anything with the same name, no check needed
function m2SetActivePageToCookie(inputActivePageId, inputValue) {

    //     
    $jq.cookie('activePageId', inputValue, { path: '/', expires: 365 });


}
/////
///// /END SECTION
/////


/**************************************************************************************
Martin H: End: New Functions for tab persistence
**************************************************************************************/


