/*
* Superliving Website Main Javascript Library
* Squiz Canberra
* February 2009
* Assumes jQuery framework is loaded.
* Use 'jQuery' instead of '$' to avoid potential JS framework conflicts i.e. prototype and jQuery in the same page.
* 
* Modification history:
* 
* 2011-04-13: Squiz Canberra
*             - File creation and initial object/function creation.
* 2012-01-25: Squiz Hobart
*             - Fixed accordion to allow closing
*
*/

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null) {
    return "";
  } else {
    return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}


var SL_GlobalScripts = {
    
    // Storage for instantiated slide show
    homeSlideShow: null,
    
    /**
     * Generic form controls.
     */
    genericFormControls: function()
    {
        
        var self = this;
        
        // Style selects.
        $("#siteSearchScope").selectBox();
        
        // Need to correct top position of select drop down for IE.
        jQuery('ul.selectBox-dropdown-menu').css('top','174px');

        // Replace any default text in input text boxes if marked with related class.
        jQuery("input[type=text].replaceDefault").focus(function() {
                if( this.value === this.defaultValue ) {
                    this.value = "";
                }
        }).blur(function() {
            if( !this.value.length ) {
                this.value = this.defaultValue;
            }
        });
        

        // Default value of the search input area
        var $query = $('#siteSearchQuery');
        var defaultVal = 'Search';
        // if search box is empty add search default text
        if($query.val().length === 0) {
            $query.val(defaultVal);
        }
       
        $query.focus(function(){
            if ($query.val() === defaultVal) {
                 $query.val('');   
            }// End if
        }).blur(function(){
            if ($query.val() === '') {
                 $query.val(defaultVal);   
            }// End if
        });
        
        
    }, // genericFormControls.
    
    
    /**
     * Set up tab content where required.
     */
    tabContent: function()
    {
        
        jQuery('#content .tabNav li a').click( function(e) {
            e.preventDefault();
            var $self = jQuery(this);
            var $parentContainer = $self.parents('.tabNav').parent();
            if($self.parent().hasClass('current')){
                return false;
            } else {
                $parentContainer.find('.current').removeClass('current');
                $self.parent().addClass('current');
                $parentContainer.find('.tabContent').addClass('removeFromView');
                $parentContainer.find($self.attr('href')).removeClass('removeFromView');
            }
        });
        
    }, // tabContent.
    
    /**
     * Dynamically apply section class to body based on current global menu selection.
     * Falls back on default grey theme if no JS. Avoids heavy maintenance overheads for CSS/Markup.
     */

    weatherContent: function()
    {   

    if ($.cookie('selectedcity') !== null) {
        var savedCity = $.cookie('selectedcity');  
        $('#weather_city').val(savedCity);
        $('#weather_output').load($('#weather_form_content').attr('action') + "?city=" + savedCity  + " #weather_output");
    } else {
        var selectedOption = jQuery('#weather_city').val();
        $.cookie('selectedcity', selectedOption, { expires: 365 });    
        var savedCity = $.cookie('selectedcity');         
        $('#weather_city').val(savedCity);    
        $('#weather_output').load($('#weather_form_content').attr('action') + "?city=" + savedCity  + " #weather_output");            
    }//end else

       $('#weather_city').change(function () {
           var selectedOption = jQuery('#weather_city').val();
           $.cookie('selectedcity', selectedOption, { expires: 365 });  
           var savedCity = $.cookie('selectedcity');  
           $('#weather_output').load($('#weather_form_content').attr('action') + "?city=" + savedCity  + " #weather_output");
       });        
    },

    applySectionThemes: function()
    {
        
        jQuery('body').addClass(jQuery('#globalNav li.current').attr('id')); 
        if(jQuery('#globalNavLineage li').length !== 0){
            $('#globalNavLineage > li:first').addClass('first');
            $('#globalNavLineage > li:nth-child(2)').addClass('second');
            $('#globalNavLineage > li:nth-child(3)').addClass('third');
            $('#globalNavLineage > li:last').addClass('last');
        } else {
            //jQuery('#globalNavLineage li:first').addClass('firstNoSibs');
        }
        if(!jQuery('#subNavWrapper ul').length){
            jQuery('#subNavWrapper').remove();
        }
        
    }, // applySectionThemes.
    
    
    addBlockQuoteCloseImage: function()
    {    
        jQuery('#article blockquote').append('<span class="block_qoute_end">&nbsp;</span>');
    },

    hideZeroComments: function()
    {    
        $('.commentCount').each(function() {
            ($(this).text() == 0) ? $(this).hide() : $(this).show();                                        
        });
    },

    pollSubmit: function () {
        $('.userPoll').closest('form').unbind('submit');
    
        $('.pollInputs :submit').click(function (e) {
            e.preventDefault();    
            var $submitButton = $(this);
            var $form = $('#' + $submitButton.attr('id').replace('_vote', ''));
            var $userPoll = $form.find('.userPoll');
            if ($form.length) {
                var $loader = jQuery('<div class="loader_image">' + '<img src="./?a=1451" alt="" style="width: 50px; height: 50px;">' + '</div>');
                $userPoll.before($loader).hide();
                var form_content = $form.serialize();
                jQuery.ajax({
                    type: "POST",
                    url: $form.attr('action'),
                    data: form_content,
                    success: function (msg) {
                        var content = $(msg).find('.userPoll').html();
                        $userPoll.html(content);
                        $loader.remove();
                        $userPoll.show();
                    }
                });
            }
        });
    
        // Also add a break inbetween the default format for poll inputs to 'format' them better
        jQuery('#rightCol .pollInputs input[type=radio]:not(:first)').before('<br />');
    },

    blogDetailsLoading: function ()
    {
     if(jQuery('#blog_select').length !== 0 ) {

     $('#blog_content_listing').addClass('removeFromView');

     function loadblogitems (selectedOption) {
     jQuery.ajax({
         type: "GET",
         url: "../configuration/asset-listings/blog-listing/blogs-listing/?" + "id=" + selectedOption,
         success: function(htmlcontent){
         var content = $(htmlcontent).find('#blog_content_listing').html();
         $('#blog_content').html(content);
         $("#blog_content").renderAds();
         }
     });
    }

    loadblogitems ($('#blog_select option:first').val());
    $('#blog_select').change( function () {
    $('#blog_content').html('<div class="loader_image" style="text-align: center"><img src="./?a=1451" alt="" style="width: 50px; height: 50px;"></div> ');
    var selectedOption = jQuery('#blog_select').val();
    loadblogitems(selectedOption);
    });

    }//end if

    },


    accordionMenu: function()
    {    
         $('ul.accordion_level2').hide();
          $('ul.accordion_level_content').hide(); 
          
          $('ul.accordion_level1 > li > a').click(function(e){
                  e.preventDefault();
                  if($(this).hasClass('current')){
                    $(this).removeClass('current').next().slideUp();  
                  }
                  else{
                    $('ul.accordion_level1 > li > a.current').removeClass('current').next().slideUp();              
                    $(this).addClass('current');
                    $(this).next().slideDown();
                  }
                  return false;
          });

          $('ul.accordion_level2 > li > a').click(function(e){
                  e.preventDefault();
                  if($(this).hasClass('current')){
                    $(this).removeClass('current').next().slideUp();  
                  }
                  else{
                    $('ul.accordion_level2 > li > a.current').removeClass('current').next('ul.accordion_level_content').slideUp();               
                    $(this).addClass('current');
                    $(this).next().slideDown();
                  }
                  return false;
          });
    },

    offerDiscountSubmit: function () {
        if($('#search_results').length === 0) {
        if($('#offersDiscountSearch').length) {
            var $form = $('#offersDiscountSearch');
            var $offersAndDiscountsContent = $('#offersAndDiscountsContent');
                $offersAndDiscountsContent.append('<div class="loader_image"><img src="./?a=1451" alt="Loading" style="width: 50px; height: 50px;"></div>');
                var form_content = $form.serialize();
                jQuery.ajax({
                    type: "GET",
                    url: $form.attr('action'),
                    data: form_content,
                    success: function (msg) {
                        var content = $(msg).find('#offers_and_discounts').html();
                        $offersAndDiscountsContent.html(content);
                    }
                });
        }//end IF
        }// end If This is not search Results page
    
    },

    addingSubMenu: function()
    {    
       // adding the global menu level two item active on hover
       jQuery('#sectionYourSay').append('<ul>' +
                 '<li><a class="polls" href="/polls"> Polls </a></li> <li><a class="forums" href="/superliving-forums"> Forums </a></li>' +
                 '<li><a class="blogs" href="/blogs"> Blogs </a></li><li><a class="expert" href="/ask-the-expert"> ASK THE EXPERT </a></li>' +
                 '</ul>');

       jQuery('#sectionExtras').append('<ul>' +
                 '<li><a class="offers" href="/offers-and-discounts"> Offers & Discounts </a></li> <li><a class="competition" href="/competitions"> Competitions </a></li>' +
                 '<li><a class="games" href="/games"> Games </a></li><li><a class="menurss" href="/rss-feeds"> RSS Feeds </a></li>' +
                 '</ul>');
    },


    validateEmail: function ()
    {
        $('#addComments #sq_commit_button').click(function(e){
            e.preventDefault();
            var emailval = $('#metadata_field_text_1368_value').val();
            
            if (emailval.indexOf('@')<0)
              {
                  $('#comment_errors').append('<ul><li>Please provide a valid email.</li></ul>');
                  return false;
               } else {
                  //$('#page_asset_builder_1352').submit();                        
               }
         });       
     
    },

    // details of the blog
    details_wysiwyg: function()
    {
       
        if(jQuery('#blog_create_location').length !== 0 ) {
            $('#blog_create_location').wrap('<div class="field_container" />');
            $('#blog_create_location').before('<label class="required" for="blog_create_location">Blog Category:</label>');

        }//end if 

    },
    
    otherSmallFunctions: function()
    { 
      //hide the question if there is no text in the question content
      if(jQuery('#question_container').length) {
          if(jQuery('#question_content').text().length === 0) {
              jQuery('#question_container').hide();         
          }
      }
      
 
      jQuery('#globalNavSubOne li:last a').css('background', 'none');

      // Start Blog Creating script
      if(jQuery('#Upload_image_to_blog').length !== 0 ) {
         window.location = $("#Upload_image_to_blog").attr("href"); //To navigate to next step while creating a blog
      } else {
              //do nothing
      }//end else    
      jQuery('#image_0_use_editor_button').css('display', 'none'); //hide the edit image button

      // If the user wishes to skip use the url parameter supplied in the query string to navigate
      var $blogButtons = jQuery('#blog_create_image_buttons');
      if ($blogButtons.length) {
          var $button = jQuery('<input type="button" value="Skip" class="sq-form-field create_blog_button" />');
          $blogButtons.append($button);
          $button.click(function(e){
              window.location = getParameterByName('url');
          });
      }
      // End Blog Creating script
      
      // Move the related content box in side the article content after second paragraph
      if ($('#articleRelatedContent').length) {
          jQuery('#article_content div p:eq(5)').append($('#articleRelatedContent'));
      }

      //Replace the Numbers of Ol and add the styled ones
      jQuery('ol').each(function(i,e){
          jQuery(this).find('li').each(function(index,elem){
          jQuery(this).find('.number').remove(); // remove any prev numbering
          jQuery(this).prepend('<span class="number">' + (index+1) + '.</span>');
          });
       }).css('list-style','none');

        // If pagination has only one child hide it
        if($("#pagination ul li").length){
            if($("#pagination ul li").length == 1)
            {
               $("#pagination").addClass('removeFromView');
            }
            else {
            //Do Nothing
            }
        }//End If #pagination exists

        // Make the twitter text division click able to the link in the feed
       jQuery('.twitter div.twtr-tweet-text').live('click',function(e){
       e.preventDefault();
        var $link = jQuery(this).find('a.twtr-hyperlink');
        window.open($link.attr('href'));   
        });

       // Search facet to move on right col
       var $facets = jQuery('div.search_facets');
       $facets.first().appendTo($('#rightCol div.facet1'));
       $facets.eq(1).appendTo($('#rightCol div.facet2'));
 
       //Remove &amps from the front end
        if(jQuery('#search_results').length) {
            var replaceAnd = jQuery('#search_results'); 
            replaceAnd.html(replaceAnd.html().replace(/&amp;amp;/g, "&amp;")); 
        }

    },//End Other Small Functions

    renderAds: function()
    {
        // Render an ad into a container
        $.fn.renderAds = function() {
        return $(this).find('div[data-banner]').each(function(){
            var AdId = $(this).attr('data-banner');
            if (typeof(OA_output) !== "undefined" &&
                OA_output.hasOwnProperty(AdId)) {
                $(this).html(OA_output[AdId]);
            }
        });
        };
    },

    searchValidate: function()
    {
        // Override default search click to validate search input first
        var $siteSearchQuery= $('#siteSearchQuery');
        var defaultVal = 'Search';
        $('#search-submit').click(function(e){ 
            e.preventDefault();
            if ($siteSearchQuery.val() !== '' && $siteSearchQuery.val() !== defaultVal) {
                if($('#siteSearchScope option:selected').val()=== "SuperLiving") {
                    $('#searchType').val('aspermont.xsl');
                    $('#fq').val('DC.ContentType:"internal"');
                    $('#siteSearch').submit();
                } else if($('#siteSearchScope option:selected').val()=== "Web") {
                      $('#searchType').val('aspermontWeb.xsl');
                      $('#fq').val('DC.ContentType:"web"');
                      $('#siteSearch').submit();

                  }//end else if
            } else {
                 alert('Please enter a search term');   
            }// End if
        });

    },

    expertsearchValidate: function()
    {
        if($('#expertSearch').length){
        // Override default search click to validate expert search input first
        var $expertSearchQuery= $('#expertSearchInput');
        var expertdefaultVal = 'Expert Question Keyword';
        $expertSearchQuery.val(expertdefaultVal); 

        $expertSearchQuery.focus(function(){
            if ($expertSearchQuery.val() === expertdefaultVal) {
                 $expertSearchQuery.val('');   
            }// End if
        }).blur(function(){
            if ($expertSearchQuery.val() === '') {
                 $expertSearchQuery.val(expertdefaultVal);   
            }// End if
        });

        $('.search_expert_button').click(function(e){ 
            e.preventDefault();
            if ($expertSearchQuery.val() !== '' && $expertSearchQuery.val() !== expertdefaultVal) {
                      $('#expertSearch').submit();
            } else {
                 alert('Please enter a search term');   
            }// End if
        });
        }// check if expert search exsists

    },

    // blog search validation (refactor this function with above when have time)
    blogsearchValidate: function()
    {
        if($('#blogSearch').length){
        // Override default search click to validate expert search input first
        var $blogSearchQuery= $('#blogSearchInput');
        var blogdefaultVal = 'Blog Search Keyword';
        $blogSearchQuery.val(blogdefaultVal); 

        $blogSearchQuery.focus(function(){
            if ($blogSearchQuery.val() === blogdefaultVal) {
                 $blogSearchQuery.val('');   
            }// End if
        }).blur(function(){
            if ($blogSearchQuery.val() === '') {
                 $blogSearchQuery.val(blogdefaultVal);   
            }// End if
        });

        $('.search_blog_button').click(function(e){ 
            e.preventDefault();
            if ($blogSearchQuery.val() !== '' && $blogSearchQuery.val() !== blogdefaultVal) {
                      $('#blogSearch').submit();
            } else {
                 alert('Please enter a search term');   
            }// End if
        });
        }// check if expert search exsists

    },

    commentFeedback: function()
    {
        //If the commenet box exsits then make thumb up thumbs down run the trigger
        if ($('.commentfeedback').length) {
            $('.commentfeedback a').click(function (e) {
                e.preventDefault();
                var $elem = $(this);
                var link = $elem.attr('href');
                
                if (jQuery(this).hasClass('feedback_submitted')) {
                    alert('You have already submitted your feedback on this comment.');
                    return false;
                }
                if (jQuery(this).hasClass('thumbsUp')) {
                     // Increment the visible count
                     var $thumbRating = jQuery(this).parent().parent().find('.thumbRating');
                     var count = parseFloat($thumbRating.text().replace(' thumbs up',''));
                     count += 1;
                     $thumbRating.text(count + ' thumbs up');
                }// End if       
                if (jQuery(this).hasClass('submit_url')) {
                    // Re-use html element from EES to display the overlay
                    var overlay = '<div id="ees_mainOverlay" style="display: block;"><div class="loading" id="ees_overlayImage"><img height="48" width="48" alt="Loading" src="/__data/ees/Images/overlay-loader.gif"></div><div id="ees_overlayMessage"></div></div>';
                    $('body').prepend(overlay);
                    $.ajax({
                        url: link,
                        context: document.body,
                        success: function () {
                            //do nothing
                            $('#ees_mainOverlay').remove();
                            if ($elem.hasClass('report')) {
                                alert('This comment has been reported to site administrators');
                            }// End if
                        }
                    });         
                    $elem.addClass('feedback_submitted').removeClass('submit_url');
                    //location.reload(); 
                }
                else {
                    //do nbothing
                }
            });
        } // end if condition for comment feed back

    },

    // modify the search results page
    searchResults: function()
    {
        if ($('#search_results').length) {           
            $.getUrlParms = function (name) {
                var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
                return results[1] || 0;
            }
            var searchOn = $.getUrlParms('siteSearchScope');        
            if (searchOn === 'Web') {
                $("#siteSearchScope").val(searchOn);
                $('.selectBox-label').text(searchOn);
            }
        } //end if search results exists

$('ul.selectBox-dropdown-menu li').removeClass().each(function(){
$('ul.selectBox-dropdown-menu li a').filter(function(i,elem){
   return $(elem).attr('rel') === searchOn;
}).parent().addClass('selectBox-selected');
});

    },

    // Account editing in an iframe lightbox overlay
    loginOverlay: function()
    {

        // Re-use html element from EES to display the overlay
        var overlay = '<div id="ees_mainOverlay" style="display: block;"><div class="loading" id="ees_overlayImage"><img height="48" width="48" alt="Loading" src="/__data/ees/Images/overlay-loader.gif"></div><div id="ees_overlayMessage"></div></div>';
            
        // If the overlay doesn't exist, prepend it
        $('#sign_in, #login_comments, a.login_link').click(function(e){
            e.preventDefault();
            if (!$('#ees_mainOverlay').length) {
                $('body').prepend(overlay);
            }// End if
            
            var $overlayContainer = $('#ees_mainOverlay');
            
            $overlayContainer.show();
            
            var editAccountURL = $(this).attr('href');
            var $iframe = $('<iframe src="javascript: false;" id="editAccount" style="padding: 40px 40px 0px;" name="editAccount" frameborder="0" width="290" height="135" /></iframe>');
            var $editContainer = $('<div id="editAccountContainer" style="box-shadow: 0px 0px 10px #f1f1f1; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; margin:50px auto 0; background:#fff; position: relative; width:380px; height:220px;"><a style="position: absolute; top: 10px; right:10px;" class="closeModal" id="close_login_box" title="Close" href="#"><!-- Close button --></a> <p style="position: absolute; font-weight: bold; top: 35px; left:30px;">Please enter you username and password to login:</p></div>');
            $overlayContainer.append($editContainer);
            $editContainer.hide();
            $('#editAccountContainer').append($iframe);
            $iframe.after('<div style="margin:0px 0 30px 50px; overflow:hidden;"><a href="/password-recovery" style="font-weight:bold; display: block; float:left;">Forgot your password?</a><a href="/join-us" style="font-weight:bold; margin-left:10px; display: block; float:left;">Register here?</a></div>');
            $iframe.bind('load',function(){
                $('#ees_overlayImage,#ees_overlayMessage').remove();
                $editContainer.show();    
                var logged_in = jQuery(this).contents().find('#you_are_logged_in').length;
                if (logged_in) {
                    $('#ees_mainOverlay').remove();  
                    location.reload();          
                }                            
            });
            $iframe.attr('src',editAccountURL);           
            
            $('#close_login_box').click(function(e){
                e.preventDefault();
                $('#ees_mainOverlay').remove(); 
                location.reload();          
             });

        });
    }

}; // End SL_GlobalScripts.



var SL_SlideShow = function(containerId)
{
    // Overall container div
    this.$container     = jQuery(containerId);
    this.baseWidth      = jQuery('#thumbnails ul li').width();
    this.extraWidth     = 4; // Account for margins, padding etc
    this.init();
    this.start();
};

SL_SlideShow.prototype = {

    interval: null,
    delay: 12,// in seconds

    init: function()
    {
        var self = this;
        
        // Bind events
        jQuery('#slideshowLeftArrow').click(function(e){
            e.preventDefault();
            self.prev();
        });
        
        jQuery('#slideshowRightArrow').click(function(e){
            e.preventDefault();
            self.next();
        });
        
        jQuery('#thumbnails ul li>a').click(function(e){
            e.preventDefault();
            self.select(jQuery(this).parent().index());
            self.stop();
        });
        
        // Select first item
        jQuery('#thumbnails ul li:eq(0)').addClass('current');
        self.select(0);

    },// End init

    start: function()
    {
	var self = this;
	self.interval = setInterval(function(){
            self.next();
        },self.delay*1000);
    },

    stop: function()
    {
	var self = this;
        clearInterval(self.interval);
    },
    
    getSelectedItem: function()
    {
        return jQuery('#thumbnails ul li.current');
    },// End getSelectedItem

    next: function()
    {
        var next = this.getSelectedItem().index()+1;
        if (next >= jQuery('#thumbnails ul li').length) {
            next = 0;
        }// End if
        this.select(next);
    },// End next
    
    prev: function()
    {
        this.select(this.getSelectedItem().index()-1);
    },// End prev
    
    select: function(index)
    {
        $items = jQuery('#thumbnails ul li');
        var total = $items.length;
        
        // Make sure we aren't exceeding any limits before selecting an item
        if (index < 0 || index > (total - 1)) {
            return false;
        }// End if
        
        // Get one item at the selected index
        var $li = $items.eq(index);
        
        // Manage class selection
        $items.removeClass('current');
        $li.addClass('current');
        
        // Count previous items
        var previousCount = $li.prevAll().length;
        
        // Count next items
        var nextCount = $li.nextAll().length;
        
        // Animate the slider to bring the selected item to the center (if applicable)
        
        if (total > 5 && previousCount > 2 && nextCount >= 2) {
            var indent = previousCount - 2;
            var width = this.baseWidth + this.extraWidth;
            var margin = width * indent;
             
            jQuery('#thumbnails ul').animate(
                {
                    marginLeft: '-' + margin + 'px'
                },500,
                function(){
                    // Animation complete
            });
        }// End if
        
        
        // We need to revert the margin to 0 if we have 2 or less items
        // before the currently selected item
        if (previousCount <= 2) {
            jQuery('#thumbnails ul').animate(
                {
                    marginLeft: '0px'
                },500,
                function(){
                    // Animation complete
            });
        }// End if

        jQuery('#imageContainer').html($li.find('.newsImage').html()).fadeOut(200).fadeIn(500);
        jQuery('#newsPanel').html($li.find('.newsContent').html()).fadeOut(200).slideDown(500);
        
    }// End select
};


jQuery(document).ready( function(){

    SL_GlobalScripts.genericFormControls();
    SL_GlobalScripts.weatherContent();
    SL_GlobalScripts.tabContent();
    SL_GlobalScripts.applySectionThemes();
    SL_GlobalScripts.hideZeroComments();
    SL_GlobalScripts.addBlockQuoteCloseImage();
    SL_GlobalScripts.otherSmallFunctions();
    // SL_GlobalScripts.validateEmail(); as two asset builder so taking email validation off
    SL_GlobalScripts.pollSubmit();
    SL_GlobalScripts.blogDetailsLoading();
    SL_GlobalScripts.accordionMenu();
    SL_GlobalScripts.offerDiscountSubmit();
    SL_GlobalScripts.addingSubMenu();
    SL_GlobalScripts.homeSlideShow = new SL_SlideShow('#homeSlideshow');
    SL_GlobalScripts.details_wysiwyg();
    SL_GlobalScripts.loginOverlay();
    SL_GlobalScripts.renderAds();
    SL_GlobalScripts.searchValidate(); 
    SL_GlobalScripts.expertsearchValidate();
    SL_GlobalScripts.blogsearchValidate();   
    SL_GlobalScripts.commentFeedback();
    SL_GlobalScripts.searchResults();
}); // End when DOM is ready.


