//**SITE AJAX HANDLING**//
//------------------------

// Called once the page has loaded
$(document).ready(function()
{

    if ($('#postContent').length > 0)
    {
        postContentTabs();
    };

    if ($('.popin').length > 0)
    {
        popin();
    };

    if ($('#miniClassList').length > 0)
    {
        classList();
    }

    if ($('#schoolSelect').length > 0)
    {
        schoolSelect();
    }

    if ($("a.reply").length > 0)
    {
        // in separate JS file - comments.js
        toggleComments();
    };

    if ($(".resultContainer").length > 0)
    {
        //resultsTabs();
    }

    //This enables all classes defines in css file
    //that should only show when javascript is enabled
    $('body').addClass('jsEnabled');

    //Disable duplicate submit button presses
    //(does not use disabled attribute so submit button name still appears in
    // form post data)
    $('form').submit(function() { $('input[type=submit]').click(function() { return false; }); });

    //Show advisory text on edit profile page if
    //user has selected to display by first name and last name
    var nameChoice = $("input[@name=NameChoice]").click(function()
    {
        $(".jsEnabled form.contentForm li span.advice").css("visibility", ($(this).val() == "true") ? "visible" : "hidden");
    }).each(function() { if ($(this).attr("checked")) $(this).click(); });

    //For old passado post display 
    if ($(".passado").length > 0)
    {

        //Wait until images loaded
        $(window).load(function()
        {
            var maxSize = $('.passado #detailText .content-preview').width();
            //Remove some pixels for margin
            maxSize = maxSize - 20;
            //Constain images to not be larger than the size of the content preview area
            $(".passado #detailText .content-preview img").each(function()
            {
                var img = $(this);
                if (img.width() > maxSize)
                {
                    img.width(maxSize);
                    img.height('auto');
                }
            });
        });
    }

    //Disable ajax for now, until ajax post working 
    return;

    /// Ajax all the forms and 'a' tags inside a Div with an .ajax class
    $("div.ajax").each(function(i)
    {
        hookUpPanelEvents($(this));
    });

});


 
// JS page interaction may have been disabled
// during an ajax call. On any error re-enable this
function handleAjaxError(panel, textStatus, errorThrown)
{
    //(TODO: Handle 500 server errors, at present errors are presented by 
    // the server as HTTP 200 OK, and this will output content of the error
    // into the html panel that was being updated)
    if (window.console && window.console.error)
    {
        console.error('ajax error:' + errorThrown + ', details: ' + textStatus);
    }
    
    //Delete throbber animation on this panel
    $('.throbber',panel).remove();
 
    //Unbind all ajax events for his panel
    $('.ajax,form',panel).unbind();
    //Re-enable interactivity for this panel:
    hookUpPanelEvents(panel);
}

//Helper method to rebind all ajax events
function rebindPage() {
    //Unbind all existing ajax events
    $('.ajax,form').unbind();

    /// Ajax-enable all the forms and a tags inside a Div with an .ajax class
    $("div.ajax").each(function(i)
    {
        hookUpPanelEvents($(this));
    });
}


/// Helper method to stop any panel
/// interactivity.
/// This is used during some ajax requests,
/// when the request completes the html for the 
/// panel will be reloaded and events rebound
function unbindPanel(panel)
{
  //  $('.ajax,form', panel).unbind().click(function() { return false; });
  //TODO Remove + fix non ajax panel links permanenetly disabled
}

//Helper method to show a 'please wait' animation while 
//a panel is being loaded
function showLoadingPanel(panel)
{
    var languageCode = getLang();

    var loadingText;
    switch (languageCode) 
    {
        case 'fr':
            loadingText = 'En cours de chargement...';
            break;
        case 'de':
            loadingText = 'Loading...';
            break;
        case 'it':
            loadingText = 'Caricamento in corso…';
            break;
        case 'es':
            loadingText = 'Cargando…';
            break;
        default:
            loadingText = 'Loading...';
    }
    
	var loadingDiv = $("<div class='throbber'>" + loadingText + "</div>");
	loadingDiv.fadeIn('slow');

	//Append within the grey box within the panel if we can, otherwise
	//just within the panel itself
	var contentFrame = $('.content-frame', panel).eq(0);
	if (contentFrame)
	{
	    contentFrame.append(loadingDiv);
	}
	else
	{
	    panel.append(loadingDiv);
	}    
	
}

//Helper method to get the locale 
//for the current webpage
function getLocale() {

    //Get string of format 'en-GB'
    var lang = navigator.language ? navigator.language : navigator.userLanguage;

    /* Ensure language code is in the format aa-AA. 
    (code logic taken from jquery localisation plugin: http://plugins.jquery.com/project/localisation) */
    lang = lang.replace(/_/, '-').toLowerCase();
    if (lang.length > 3) {
        lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
    }

    return lang;
}

//Return just first two characters of locale
//to get the language code only
function getBrowserLang() {
    var locale = getLocale();
    if (locale.length < 2)
        return '';
    return locale.substring(0, 2);
}


//Get the language of the current page
function getLang() {

    //Default to language subdomain
    var domain = document.domain.toLowerCase();
    if ((domain.length >= 3) && (domain.substring(2,3)=='.')) {
        return domain.substring(0,2);
    }
  
    //Go on browser locale instead 
    return getBrowserLang();
}

//Helper method to ajax-ify a particular panel
function hookUpPanelEvents(panel)
{
    //Use jquery forms extension library
    //to turn all html forms into
    //an asynchronous ajax call
    $("form", panel).each(function(index, element)
    {

        //Get reference to form
        var form = $(element);

        //Get reference to action for this form 
        var action = form.attr('action');

        //Don't ajax anything if not action found 
        if (!action) return;

        //Does this form contain a PopIn hidden field?
        //TODO:
        //if ($(input[type = "hidden"][name = "PopIn"], form).length > 0)
        //{
            //Set the panel as the fixed PopIn element
        //    $('#PopIn'
       // }

        //If so the panel is fixed as PopIn, the action 
        //url is the hidden PopIn field 

        //Ajax-ify this form
        form.ajaxForm(
        {
            success: function(data)
            {
                //Turn the raw data into a jquery DOM object
                var html = $(data);

                //Act on any embedded refreshes and redirects
                //in the output
                var isRedirect = handleRefreshesAndRedirects(html);

                //if redirecting no further action
                if (isRedirect) return;

                //Replace this panel with the updated html
                panel.html(html);

                //Add javascript interactivity to
                //this new html
                hookUpPanelEvents(panel);
            },
            url: getAjaxUrl(panel, action),
            beforeSubmit: function(data, form, options)
            {
                //No action if url not set
                //(TO DO - show error in this case)
                if (!options.url) return false;

                //Just before starting the ajax call,
                //turn off all other click events and 
                //other interaction in this panel.
                unbindPanel(panel);

                //Show a 'please wait' animation
                showLoadingPanel(panel);

            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
                handleAjaxError(panel, textStatus, errorThrown);
            }
        });
    });
    
	/// For all hyperlinks marked with an 
	//  ajax css class, turn these into 
	//  an asynchronous ajax request to 
	//  update the html for just this panel.
	//
	//  The regular non-ajax hyperlink would update the whole page 
    //  including this panel with the inputs this panel needs on 
    //  the querystring. 
    //
    //  When a link is css-marked as 'ajax'-able, an assumption is made 
    //  that the same querystring can be transplanted onto a page request for 
    //  just this panel html, and the page for this single control
    //  will pull out the inputs it needs from the querystring and do
    //  the right thing.
    $("a.ajax", panel).each(function(i)
    {
        //Add a new anonymous function
        //to run when clicking any ajax-able hyperlink
        $(this).click(function()
        {
          
            //Get the current hyperlink url
            var sourceUrl = $(this).attr("href");

            //Get ajax version of this url
            var url = getAjaxUrl(panel, sourceUrl);

            //Let original non-ajax hyperlink run if no panel details found
            if (!url) return true;

            //Prevent any other actions on this panel while this link being followed
            unbindPanel(panel);

            // Show loading screen
            showLoadingPanel(panel)

            // Call helper method make ajax request
            // for this panel
            ajaxGet(panel, url);

            //return false to prevent
            //the original hyperlink from firing
            return false;
        });
    });
}

//Helper method to make an 
//ajax request to get the html for one panel
function ajaxGet(panel, url)
{
    //Make an ajax http GET request
    $.ajax(
	{
		url: url,
		async: true,
		type: "GET",
		success: function(data)
		{
		    //When the ajax request has completed, 
		    //replace this panel with the updated html
			panel.html(data);
			//Add javascript interactivity to
			//this new html
			hookUpPanelEvents(panel);

        },
		error: function (XMLHttpRequest, textStatus, errorThrown)
		{
		    handleAjaxError(panel, textStatus, errorThrown);		    
		}
	});
}

//Helper method to get the ajax url for a given ajax element
function getAjaxUrl(panel, sourceUrl)
{
    //Get control name 
    var controlName = panel.attr("name");

    //Retrun null ajax url if no control name found
    if (!controlName) return null;

    //Append 'ajax' start to url then control name
    var url = '/ajax/' + controlName;

    //Append source Url
    url += sourceUrl; 

    //Append a unique date/time to force the url to be unique,
    //if noCache parameter found on the panel 
    if (panel.attr("noCache"))
    {
        var foundQuerystringParameters;
     
        var questionMarkStart = sourceUrl.indexOf('?');
        if (questionMarkStart > -1)
        {
            foundQuerystringParameters = true; 
        }
    
        if (foundQuerystringParameters) url += '&'; else url += '?';
        url += 'nc=' + Date();
    }
    
    return url;
}

        
//Helper method to act on any refresh or redirect
//hints in the html of an ajax response
function handleRefreshesAndRedirects(html)
{
    //Hints to redirect to a new page will be embedded
    //as a hidden input element - look for this
    var redirUrl = $("input[@name=redirectPage]", html).val();

    //If found,
    if (redirUrl)
    {
        //Redirect the client browser
        document.location.href = redirUrl;
		
        //No other action
        return true; 
    }

    //Hints to refresh other panels on the page will be 
    //embedded as a hidden input element in the output output.
    //Attempt to retrieve a comma separated list of panels to
    //refresh 
    var redirPanel = $("input[@name=refreshPanel]", html).val();
    
    //If found,
    if (redirPanel)
    {
        //Loop through control names
        var panels = new Array();
        panels = redirPanel.split(',');
        for (var i = 0; i < panels.length; i++)
        {
            //For each control loop through all on-screen 
            //panels of that control type
            $("div[@name=" + panels[i] + "]").each(function()
            {
                //Get jquery DOM object reference for this panel
                var panel = $(this);

                var sourceUrl = document.location;

                //Get the panel url
                var url = getAjaxUrl(panel, sourceUrl);

                // Call helper method make ajax request
                // for this panel if ajax url found               
                if (url)
                    ajaxGet(panel, url);
            });
        }
    }
    
    return false;
}

//Handle compose post
//-------------------
function postContentTabs(){
    var currentTab;
    function textTab()
    {
        $('#imageupload').fadeOut('fast', function(){
            $('#imagepostfields').hide('normal', function(){ //.slideUp
                $('#videopostfields').hide('normal'); //.slideUp
            });
        });
        if(currentTab != 'text'){
            getSubmitButton($('.textSubmit'));
        };
        setPostType('text');
    };    

    function videoTab(){
        $('#imageupload').fadeOut('fast',function(){
            $('#imagepostfields').hide('normal', function(){ //.slideUp
                $('#videopostfields').show('normal'); //.slideDown
            });
        });
        if(currentTab != 'video'){
            getSubmitButton($('.videoSubmit'));
        };
        setPostType('video');
    };    

    function imageTab(){
        $('#videopostfields').hide('normal', function() //.slideUp
        {
            $('#imagepostfields').show('normal', function(){
                $('#imageupload').fadeIn('fast');
            });  //.slideDown('normal');           
        });

        //$('#imageupload').show('normal');
        if(currentTab != 'image'){
            getSubmitButton($('.imageSubmit'));
        };
        setPostType('image');
    };

    function getSubmitButton(thisSubmitButton)
    {
            $('ul li.submitForm input').fadeOut();
            $(thisSubmitButton).fadeIn();
    };

    function setPostType(postType)
    {
        var v;
        if (postType == 'text') v = 8;
        if (postType == 'image') v = 2;
        if (postType == 'video') v = 4;
        
        if (!v) return;

        $('input[name=PostTypeAsInt]').val(v);
        currentTab = postType;
    }

    function getPostType()
    {
        var p = $('input[name=PostTypeAsInt]').val();
        if (p==8 || p==1) return 'text';
        if (p==2) return 'image';
        if (p==4) return 'video';
        return 'unknown';
    }



  //Add click event for each tab
     $('#postContentNav li').each(function()
     {
         $(this).click(function()
         {
             //Hide all tabs
             $('#postContentNav li').removeClass('on');

             //Show this tab
             var thisLi = $(this);
             thisLi.addClass('on');

             //Show all form fields 
             $('#postContent .contentForm').find('li:gt(0)').show();  //.slideDown('normal');

             //Configure field display depending on tab selected 
             if (thisLi.attr('id') == 'posttext')
             {
                 textTab();
             } else if (thisLi.attr('id') == 'postvideo')
             {
                 videoTab();
             } else if (thisLi.attr('id') == 'postimage')
             {
                 imageTab();
             }
             return false;
         });
     });

    //Only if no compose post validation errors
    if (!$('#ComposeErrors').hasClass('errorResponse'))
    {
        //Enable compose module show/hide:

        //Hide all display fields after the 'title' field
        $('#postContent .contentForm').find('li:gt(0)').hide();

        //If click anywhere outside of post content, 
        //hide the form fields 
        $('html').click(function()
        {
            $('#imageupload').hide();
            $('#postContent .contentForm').find('li:gt(0)').hide('normal') //.slideUp();
        });

        //If click anywhere in postContent, show all hidden fields
        $('#postContent > *').click(function(event)
        {
            event.stopPropagation();
            $('#postContent .contentForm').find('li:gt(0)').show('normal'); //.slideDown();
        });
        
    } else {
        //Set initial tab view for this display
        var postType = getPostType();
        if (postType == 'text') $('#posttext').click();
        if (postType == 'video') $('#postvideo').click();
        if (postType == 'image') $('#postimage').click();
    }
    

   

    
};

function bigLinks(){
    $('#contentList > li, #clubList > li, #inbox > li, #selectedClub ul > li').each(function(){
        var $thisBox = $(this);
        $thisBox.mouseover(function(){
            $thisBox.addClass('hover');
        }).mouseout(function(){
            $thisBox.removeClass('hover');
        }).click(function(){
            window.location = $thisBox.find('a:first').attr('href');
        });
    })
};
function popin(){
    $('.popin').append('<span class="corner tl"></span><span class="corner tr"></span><span class="corner bl"></span><span class="corner br"></span><span class="vert ts"></span><span class="vert bs"></span><span class="horz ls"></span><span class="horz rs"></span>');
    
    var sdHeight = $('.popin').height()-80;
    var sdWidth = $('.popin').width()-80;
    $('.ls, .rs').css('height',sdHeight)
    $('.ts, .bs').css('width',sdWidth)
    
    $('.popin').fadeIn();

    $('.popin a.drag').mousedown(function(e){
	    yOffset = e.pageY - (parseFloat($('.popin').css('top')));
        xOffset = e.pageX - (parseFloat($('.popin').css('left')));

        $('.popin').bind('mousemove',function(e){
	        $(this)
	            .css("top",(e.pageY - yOffset) + "px")
	            .css("left",(e.pageX - xOffset) + "px");
        })
        return false;
    }).mouseup(function(){
        $('.popin').unbind('mousemove');
    });
    
    $('body').toggleClass('hideOverflow')
    
    //TODO - fade out popin, not currently implemented
    $('.popin a.close').click(function(){
        $('.popin').fadeOut(function(){
            //$(this).remove();
        })
        $('body').toggleClass('hideOverflow')
        //return false;
    });
};

//Hook into class list drop-down
//selecting from list 
function classList()
{
    var select = $('#miniClassList label select').eq(0);
    if (!select) return;

    select.change(function()
    {
        var year;
        year = $('option:selected', select).text();
        window.location.hash = year;
    });
}

//Hook into school drop-down
function schoolSelect()
{
    //No action if not single column list
    if ($('#schoolSelect ol.singleColumn').length == 0) return;

    $('#schoolSelect ol.letterNav li').click(function(event)
    {
        //Stop hyperlink from triggering    
        event.stopPropagation();

        //Highlight this letter only 
        $('#schoolSelect ol.letterNav li').removeClass("on");
        $(this).addClass("on");

        //Hide all ol lists
        $('#schoolSelect ol.singleColumn').hide();

        //Attempt to find a link within clicked li 
        var name = $(this).attr("linkref");

        //No action if not found
        if (!name) return;

        //Find ol list referred to by this tag
        var olList = $('#schoolSelect ol li a[name=' + name + ']').parent().parent();

        //Show this particular list
        olList.show();

    });

    /* Resizing to largest height disabled
    var largestHeight = 0;
    //Loop through all lists, calculate largest height
    $('#schoolSelect ol.singleColumn').each(function()
    {
        var height = $(this).height();
        if (largestHeight < height)
        {
            largestHeight = height;
        }
    });

    //Set all columns to largest height, if less
    //than 1080px
    if (largestHeight <= 1080)
        $('#schoolSelect ol.singleColumn').height(largestHeight);
    */

    //Disable all hyperlinks on letter navigation
    $('#schoolSelect ol.letterNav li a').each(function()
    {
        var href = $(this).attr("href");
        if (!href || href.length < 2) return;
        href = href.substring(1);
        $(this).parent().attr("linkref", href);
        $(this).attr("href", "#");
    }); 

    //Auto-click first letter
    $('#schoolSelect ol.letterNav li').eq(0).click(); 
           
   }

// nedstats site stat 4 code  
function sitestat(ns_l)
{
    ns_l += '&amp;ns__t=' + (new Date()).getTime(); ns_pixelUrl = ns_l;
    ns_0 = document.referrer;
    ns_0 = (ns_0.lastIndexOf('/') == ns_0.length - 1) ? ns_0.substring(ns_0.lastIndexOf('/'), 0) : ns_0;
    if (ns_0.length > 0) ns_l += '&amp;ns_referrer=' + escape(ns_0);
    if (document.images) { ns_1 = new Image(); ns_1.src = ns_l; } else
        document.write('<img src="' + ns_l + '" width="1" height="1" alt="">');
} 




// results tabs ////////////////////////////////////////////////////////////////////////
function resultsTabs (){

    // create tabs container
    $("h2#searchSummary").before('<ul id="searchResultTabs"></ul>');
    
    // create arrays
    var tabTotal = new Array();
    var tabTitle = new Array();
    var newId = new Array();
    var currentIndex;
    
    $(".resultContainer").each(function(i){
        // set variables
        tabTotal[i] = parseFloat($(this).find('h3 > strong').text());
        tabTitle[i] = $(this).find('h3 > span').text();
        newId[i] = $(this).attr('id').replace(/Results/,"")
        
        var tabClass;
        if (tabTotal[i] != 0){
            tabClass = 'on'
        } else {
            tabClass = 'off'
        };
        
        // create tab
        $('#searchResultTabs').append('<li id="'+newId[i]+'Tab" class="'+tabClass+'"><a href="#">'+tabTitle[i]+' ('+tabTotal[i]+')</a></li>');
        //$(this).hide();
    });
    
    // show or hide on click of tab
    $('#searchResultTabs li:not(.off)').each(function(i){
        $(this).click(function(){
            var results = '#'+newId[i]+'Results';
            if (currentIndex != i){
                $('.resultContainer:visible').hide();
                $(results).show();
                
                $('#searchResultTabs li').removeClass('currentTab');
                $(this).addClass('currentTab');
                return false;
            };
            currentIndex = i;
        });
    })
    
    // choose default tab to show
    // gets highest total to display first
    function onPageLoad(){
        $(".resultContainer").each(function(){
            $(this).hide();
        });
        var firstTab;
        var url = window.location.href;
        var endString = url.substring(url.lastIndexOf("&"))
        
        if (endString.match("&G.P=")){
            firstTab = 'li#'+newId[0]+'Tab'
        } else if (endString.match("&p=")){
            firstTab = 'li#'+newId[1]+'Tab'
        } else {
            var highestTotal = Math.max.apply(null, tabTotal);
            var elementIndex=-1;
            for(var n=0;n<tabTotal.length;n++){
                if(tabTotal[n]== highestTotal ){//if matches break from loop and get the index
                    elementIndex=n;
                }
            }
            firstTab = 'li#'+newId[elementIndex]+'Tab'
        };
        $(firstTab).click();
        
        
    }
    onPageLoad ();
        
}