// Admin tabs plugin
(function() {
  jQuery.fn.prevWrap = function(){
    var prev = jQuery(this).prev();
    if(prev.length) return prev;
    return jQuery(this).siblings().filter(':last-child');
  };
  jQuery.fn.nextWrap = function(){
    var next = jQuery(this).next();
    if(next.length) return next;
    return jQuery(this).siblings().filter(':first-child');
  };
})();


(function() {
  jQuery.fn.i3Tabs = function(){
      var container = $(this);
      var tabHeaders = container.children('.mainTabs').children('li');
      var tabs = container.find('.MSTabs_container');
      tabs.hide();
      tabHeaders.children('a').click(function(e){
        e.preventDefault();
        tabHeaders.removeClass('active');
        jQuery(this).parent().addClass('active');
        tabs.filter('.active').hide().removeClass('active');
        jQuery(this.hash).addClass('active').show();
      });
      var current = tabHeaders.filter('.active');
      if(current.length)
      {
        jQuery(current).children('a').click();
      } else {
        tabHeaders.filter(':first-child').children('a').click();
      }
      // Add scrolling
      container.children('.mainTabs').wheel(function(e,d){
        if(d>0)
        {
          tabHeaders.filter('.active').prevWrap().children('a').click();
        }
        else
        {
          tabHeaders.filter('.active').nextWrap().children('a').click();
        }
        return false;
      });
  };
  // Really?   
  //$('a','div.banner').attr('target','_blank'); 
})();             


$(document).ready(function() 
{
    //$(".media_nopad").media({autoplay: true});
    $('.show_media').hide();
    $('.enable_preview').click(function(){    
        $('.show_media').hide(); 
          $('#media-'+$(this).attr('rel')).toggle();
    });
    
    $('.slider').slider(
    {
        min:1,
        max:10,
        steps:10,
        change: function()
        {
            rel = $(this).attr('rel');
            $('#attribute'+rel).val($('#slider'+rel).slider('value'));
        }
    });

    $('#a_toggle').click(function(){$('#CMS-ANNOUNCEMENTS').slideToggle();});                                                     
    $('#a_infoToggle').click(function(){$('#imageInfo').slideToggle();});
    
    $.fn.media.defaults = { 
    preferMeta:    1,         // true if markup metadata takes precedence over options object 
    autoplay:      1,         // normalized cross-player setting 
    bgColor:       '#ffffff', // background color 
    params:        {'wmode':'transparent','allowfullscreen':'true'},        // added to object element as param elements; added to embed element as attrs
    attrs:         {},        // added to object and embed elements as attrs 
    flashvars:     {},        // added to flash content as flashvars param/attr 
    flashVersion:  '8',       // required flash version 
 
    // default flash video and mp3 player 
    // @see: http://jeroenwijering.com/?item=Flash_Media_Player 
    flvPlayer:     '/_ui/flash/mediaplayer.swf', 
    mp3Player:     '/_ui/flash/mediaplayer.swf', 
     
    // Silverlight options 
    // @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx 
    silverlight: { 
        inplaceInstallPrompt: 'true', // display in-place install prompt? 
        isWindowless:         'true', // windowless mode (false for wrapping markup) 
        framerate:            '24',   // maximum framerate 
        version:              '0.9',  // Silverlight version 
        onError:              null,   // onError callback 
        onLoad:               null,   // onLoad callback 
        initParams:           null,   // object init params 
        userContext:          null    // callback arg passed to the load callback 
    } 
    }; 
    
    $('.toggleLink').click(function(e){        
      e.preventDefault();
      
      if (this.hash)
        $(this.hash).slideToggle('slow');
      
      if (this.rel)
        $(this.rel).slideToggle('slow');
    });

    $('.toggleMe').click(function(e){
      e.preventDefault();

      if (this.hash)
        $(this.hash).toggle();

      if (this.rel)
        $(this.rel).toggle();
    });
    
    $('.toggle:first').click();
    
    $('.select_all').click(function(e){
        e.preventDefault();
        $('input:checkbox').attr('checked',true); 
    }); 
    $('.select_invert').click(function(e){
        e.preventDefault();         
        $('input:checkbox').each(function(){       
            if($(this).attr('checked'))
                $(this).attr('checked',false);
            else
            {
                if(!$(this).attr('disabled'))
                $(this).attr('checked',true); 
            }
        })
    });

    $('.scrollPage').click(function() {
        var elementClicked = $(this).attr("rel");
        var destination = $(elementClicked).offset().top;
        $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-26}, 850 );
        return false;
    });
    
    $(".showCalendar").click(function(e){
           e.preventDefault(); 
           $("#calendar_container").toggle(); 
        });
    
// Image Scroller on labels

        $('#releaseSlides').serialScroll({
            items:'div',
            prev:'.prevSlide',
            next:'.nextSlide',
            axis:'x',
            //offset:-10,//when scrolling to photo, stop 230 before reaching it (from the left)
            start:0, //as we are centering it, start at the 2nd
            duration: 700,
            force:false,
            interval: 0,
            constant: true,
            step: 5,
            exclude: 4,
            stop:true,
            lock:false,
            cycle:false, //don't pull back once you reach the end
            jump: false //click on the images to scroll to them
    });


    // news and press Scroller on Homepage
    var news_loaded_counter = 0;
    var current_news = 1;
    
    $('#moreNewsSlider').serialScroll({
            items:'div.moreNews',
            prev:'.prevSlide',
            next:'.nextSlide',
            axis:'x',
            //offset:-10,//when scrolling to photo, stop 230 before reaching it (from the left)
            start:0, //as we are centering it, start at the 2nd
            duration: 500,
            force:false,
            interval: 0,
            constant: true,
            step: 2,
            stop:true,
            lazy:true,
            lock:false,
            exclude:1,
            cycle:false, //don't pull back once you reach the end
            jump: false //click on the images to scroll to them
    });
    
    $('#loadMoreNews').click(function(){

        if(news_loaded_counter <= current_news - 1)
        {
            window.fetchContent({p:current_news+5,rpp:2,content_type:'CmsPage',sort:'is_featured DESC, published DESC',params:'cms_sections_id=1'}, function(data) {dressMoreNews(data)});
            news_loaded_counter++;
        }
        current_news++;
    }).click();
    
    $('#revertMoreNews').click(function(){
        $('#loadMoreNews').show();
        current_news--;
    });


});

function dressMoreNews(news)
{
    for(i in news)
    {
        var html = '<div class="moreNews left"><ul><li class="thumb"><img src="/resize/?img='+news[i]['image']+'&amp;w=114&amp;h=75"></li><li class="date">'+news[i]['dateFormatted']+'</li><li class="title"><a href="'+news[i]['shortname']+'">'+news[i]['title']+'</a></li><li class="readMore"><a href="'+news[i]['shortname']+'">Read More</a></li></ul></div>';
        $('div#moreNewsList').append(html)
    }
}

window.fetchContent = function(params,decorator)
{
    $.ajax({
         url:'/pages_actions/std/cms_fetch_content.php',
         type: 'POST',
         dataType: 'json',
         data: params,
         async: false,
         success: function(data)
         {
             if(data.error)
             {
                alert(data.error_message);
             }
             else
             {
                if (data.results)
                {
                    if(decorator)
                    {
                        decorator(data.results);
                    }
                }
             }
         }
    });
}
 
 
  function updateHiddenField(field,theValue){
    $('#'+field).val(theValue).change();
  }
 
    function popUp(URL) 
    {
        day = new Date();
        id = day.getTime();
        eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=800,height=700,left = 440,top = 250');");
    }                  
    function GetValueFromChild(myVal)
    {
        document.getElementById('cms_templates_id').value = myVal;
    }

/* Steps rollover display */
(function() {
  jQuery.fn.stepsRollover = function(){
      var containers = $(this).children();
      
      for (var i=0; i<containers.length; i++)
      {
        if (containers[i].parentNode.offsetHeight < containers[i].offsetHeight - 5)
            $(containers[i]).addClass('more');
            
        $(containers[i]).each(function()
        {
            this.__height = this.parentNode.offsetHeight;
            if (this.parentNode.offsetHeight < this.offsetHeight - 5)
            {
                //$(this.parentNode).addClass('extended');
                //this.parentNode.style.overflow = 'visible';
                //this.parentNode.style.height = 'auto';
                $(this.parentNode).attr("title", "header=[] cssheader=[tooltipHeader] cssbody=[tooltipBody] body=['" + $(this.parentNode).text() + "']");
            }
        });
        
        /*
        $(containers[i]).mouseout(function()
        {
            $(this.parentNode).removeClass('extended');
            //this.parentNode.style.overflow = 'hidden';
            //this.parentNode.style.height = this.__height+'px';
        });
        */
        
      }
  };
})();

function inArray (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;}
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                
                return true;
            }
        }
    }
     return false;
}

window.editImage = function(path)
{
    var container = $('#edit_image');
    if (container.length == 0)
    {
        $(document).find('body').append("<div id='edit_image' style='display: none'></div>");
        container = $('#edit_image');
    }
    
    container.html('<iframe style="width:100%; height:100%; border: 0px" src="/images_editor/?src='+path+'"></iframe>');
    container.dialog({            
    autoOpen: true,               
    width: 1000,     
    height: 720,   
    title: 'MagicFM Images Editor',     
    modal: true,
    close: function(){
        container.remove();
        $(this).dialog('destroy');
    }});
}

window.editVideo = function(path)
{
    var container = $('#edit_video');
    if (container.length == 0)
    {
        $(document).find('body').append("<div id='edit_video' style='display: none'></div>");
        container = $('#edit_video');
    }
    
    container.html('<iframe style="width:100%; height:100%; border: 0px" src="/videos_editor/?src='+path+'"></iframe>');
    container.dialog({            
    autoOpen: true,               
    width: 1000,     
    height: 720,   
    title: 'MagicFM Videos Editor',     
    modal: true,
    close: function(){
        container.remove();
        $(this).dialog('destroy');
    }});
}

window.loadComments = function(container, cms_content, cms_content_id, rpp, p)
{
    $.ajax({
        url: '/pages_actions/std/cms_content_paginate_comments.php',
        data: {'cms_content': cms_content,
               'cms_content_id': cms_content_id,
               'rpp': rpp,
               'p': p},
        success: function(data)
        {
            container.html(data);
        }        
    })
}

window.trim = function(string)
{
    if (string)
    {
        var trimmed = string.replace(/^[\t\n ]/g,'').replace(/[\t\n ]$/g,'');
        return string == trimmed ? string : window.trim(trimmed);
    }
    else return string;
}
