/**
*	Author: Jarrett M. Barnett
*	E-mail: jarrett@mc2design.com
*	Company: MC2 Design Group, Inc.
*	Copyright (c) 2009
*	Last Modified: 2010-01-27
*/

/** NOTES:
 *      initCustomFuctions() initiates custom functions that extend jQuery's library.
 *      initSearch() makes search input field clear onfocus, only when search hasn't been performed.
 *      initExtlinks() initiates external linking rules, such as rel="external", and class="noclick".
 *      initAjax() is a basic AJAX function that can be reused. It's built to really only handle one specific class usage,
 *               as most sites only need just that. Additional AJAX functions can be added here as required. Simply create
 *               the function and add it to the "jquery ready" function just below these notes.
 *
 *   BUILT FOR JQUERY v1.3.2
 */


// jquery ready
$(function () {
    initCustomFunctions();
    initSearch();
    initExtlinks();
    initAjax();
    //initNavigation();
    //initColorbox();
    initSignup();
    //initGallery();
    initSlideshowcontrols();
});

function initCustomFunctions(){
    $.fn.delay = function(duration) {
        $(this).animate({ dummy: 1 }, duration);
        return this;
    };
}

function initSearch(){
    var _search = $('input#search');
    var _defaultvalue = "enter keywords";

    // On focus of search field, clear it unless user keywords exist
    _search.focus(function(){
        _searchvalue = $(this).val('');
        // only erase if user hasnt already performed a search
        if(_searchvalue == 'enter keywords') $(this).val('');
    });
}

function initExtlinks(){
    var _extlinkclass   =   $('a:external');
    var _extlink        =   $('a[rel="external"]');
    var _noclick        =   $('a.noclick');

    // Creating custom :external selector
    $.expr[':'].external = function(obj){
        return !obj.href.match(/^mailto\:/)
                && (obj.hostname != location.hostname);
    },
        // Add 'external' CSS class to all external links
        _extlinkclass.attr('rel', 'external'),


    // Open External Links In New Window
    _extlink.click(function(){
        $(this).attr('target','_blank');
    }),

    // Links that have class of noclick not direct to target href
    _noclick.click(function() {
        return false;
    });
}

function initAjax(){
    var _eventid        =   $('a.ajax'); // what element activates the AJAX
    var _dataurl        =   ''; // URL of page to have AJAX fetch
    var _dataattr       =   'href'; // attribute with URL
    var _type           =   'GET'; // GET or POST
    var _contentwrapper =   $('#ajax_content'); // content area that is populated by AJAX
    var _loadingwrapper =   $('#loading'); // loading div identifier for user friendly "progress bars"
    var _hidecontent    =   true; // true or false, true will enable the fancier "effects" for the show/hide of AJAX content
    var _datatype       =   'html';

    _eventid.click(function () {
        // stop existing animations
        _contentwrapper.stop(false,true);

        //hide the content and show the progress bar
        if (_loadingwrapper) _loadingwrapper.show();

        var _data = $(this).attr(_dataattr); // data needed to be passed

        // ajax function
        $.ajax({
            url: _dataurl + _data,
            type: _type,
            dataType: _datatype,
            cache: false,
            success: function (html) {

                //hide the progress bar
                if (_loadingwrapper) _loadingwrapper.hide();

                // add retrieved content into _contentwrapper
                if(_hidecontent == true) {
                    _contentwrapper.animate({opacity: 0, bgColor:'#fff'}, 0, null, function(){
                        _contentwrapper.html(html);
                    });
                } else {
                    _contentwrapper.html(_content);
                }
                //display the content (available effects here: http://docs.jquery.com/Effects )
                _contentwrapper.animate({opacity: 1,bgColor:'#000'}, 2000); // show(1500), fadeIn(1500), slideDown(1500), animate({width: "100%", opacity: 0.4}, 1500)
            }
        });// end ajax

        return false;

    });// end click function
}

function initNavigation(){
    //****************************/
    // click action for left nav, fluid show/hide
    $("#menu li.parentcat").hover(
        function(){
               $(this).delay(1200).addClass('active').find("ul").slideDown(500);
            },
        function(){
                $(this).removeClass('active').find("ul").hide();
                return false;
    });
}

function initPreloader(){


    jQuery.preloadImages = function()
    {
      for(var i = 0; i<arguments.length; i++)
      {
        jQuery("<img>").attr("src", arguments[i]);
      }
    }

    $(document).ready(function(){
            $.preloadImages(
                    // design elements
                    "/themes/nevinandwitt/assets/graphics/sb-menu-active.gif",
                    "/themes/nevinandwitt/assets/graphics/more-active.png"
            );
    }); // end jQuery


}

function initColorbox(){
                //Examples of how to assign the ColorBox event to elements
                $("a[rel='example1']").colorbox();
                $("a[rel='example2']").colorbox({transition:"fade"});
                $("a[rel='example3']").colorbox({transition:"none", width:"75%", height:"75%"});
                $("a[rel='example4']").colorbox({slideshow:true});
                $(".single").colorbox({}, function(){
                        alert('Howdy, this is an example callback.');
                });
                $(".colorbox").colorbox();
                $(".youtube").colorbox({iframe:true, width:650, height:550});
                $(".iframe").colorbox({width:"80%", height:"80%", iframe:true});
                $(".inline").colorbox({width:"50%", inline:true, href:"#inline_example1"});

                //Example of preserving a JavaScript event for inline calls.
                $("#click").click(function(){
                        $('#click').css({"background-color":"#9F9F9F", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
                        return false;
                });
}

function initSignup(){
    $('#newsletterform').submit(function(){
        _error = false;
        _emailfield = $('#email');
        _emailaddress = _emailfield.val();
        _emailfield.removeClass('error');
        _posturl = '/forms/newsletter/?';
        _postdata = 'em='+encodeURIComponent(_emailaddress);
        _type = 'GET';

        if(_error == false) {
                $.ajax({
                      url: _posturl + _postdata,
                      type: _type,
                      cache: false,
                      success: function(data){

                          if(data == 'Success! Thank you for subscribing!'){
                              $("form#newsletterform div.text").hide(),
                              $("div.sign-input").hide();
                              $("#signupmessage").addClass('success').removeClass('error');
                          } else {
                              $("#signupmessage").addClass('error');
                          }
                          
                        document.getElementById('signupmessage').innerHTML = data;
                        $("#signupmessage").show(1200);
                        
                      }
                }); // end ajax
                return false;
        } else {
            _error = true;
            _emailfield.addClass('error');
        } // end error check
    })
}

function initGallery() {
    $('#gallerycycle').cycle({
    fx:     'fade',
    speed:  'fast',
    timeout: 0,
    next:   '.next',
    prev:   '.prev'
    });
}

function initSlideshow() {

    var _play   = $('a.play');
    var _pause  = $('a.pause');

    var $active = $('#gallerycycle ul li.active');
    var $activedesc = $('#gallerydesc ul li.active');

    if ( $active.length == 0 ) $active = $('#gallerycycle ul li:last');
    if ( $activedesc.length == 0) $activedesc = $('#gallerydesc ul li:last');
    var $next     = $active.next().length ? $active.next() : $('#gallerycycle ul li:first');
    var $nextdesc = $activedesc.next().length ? $activedesc.next() : $('#gallerydesc ul li:first');

    $active.addClass('last-active');
    $activedesc.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 700, function() {
            $active.removeClass('active last-active');
            $active.animate({opacity: 0.0}, 700);
    }),
    $nextdesc.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 0, function() {
            $activedesc.removeClass('active last-active');
            $activedesc.animate({opacity: 0.0}, 0);
    })

        // swap buttons
        _play.removeClass('active'),
        _pause.addClass('active');

}
function initSlideshowcontrols(){

    // Controls
    var _prev   = $('a.prev');
    var _next   = $('a.next');
    var _play   = $('a.play');
    var _pause  = $('a.pause');

    var _playcontrol = $('#playcontrol');
    var _slideshowid = $('#gallerycycle ul li');
    var _slideshowdescid = $('#gallerydesc ul li');

    // Autostart Slideshow
    var _currentid = setInterval(initSlideshow, 5000 ); _playcontrol.attr('rel', _currentid);

    // Previous Button
    _prev.click(function(){

        var _currentid = _playcontrol.attr('rel'); clearInterval(_currentid);

        _slideshowid.stop(false,true);

        // run slideshow one time (to next slide)
        var $active = $('#gallerycycle ul li.active');
        var $activedesc = $('#gallerydesc ul li.active');

        _slideshowid.removeClass('active last-active');
        _slideshowdescid.removeClass('active last-active');
        if ( $active.length == 0 ) $active = $('#gallerycycle ul li:last');
        if ( $activedesc.length == 0 ) $activedesc = $('#gallerydesc ul li:last');

        var $prev =  $active.prev().length ? $active.prev() : $('#gallerycycle ul li:last'); // get prev
        var $prevdesc =  $activedesc.prev().length ? $activedesc.prev() : $('#gallerydesc ul li:last'); // get prev

        $prev.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 0, function() {
                $active.removeClass('active last-active');
                $active.addClass('last-active');
                $active.animate({opacity: 0.0}, 0);
                // run slideshow
                var _currentid = setInterval(initSlideshow, 5000 ); _playcontrol.attr('rel', _currentid);
        }),
        $prevdesc.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 0, function(){
                $activedesc.removeClass('active last-active');
                $activedesc.addClass('last-active');
                $activedesc.animate({opacity: 0.0}, 0);
                // run slideshow

        });
        return false;
    });

     // Next Button
    _next.click(function(){

        var _currentid = $('#playcontrol').attr('rel'); clearInterval(_currentid);

        // run slideshow one time (to next slide)
        var $active = $('#gallerycycle ul li.active');
        var $activedesc = $('#gallerydesc ul li.active');
        if ( $active.length == 0 ) $active = $('#gallerycycle ul li:last');
        if ( $activedesc.length == 0 ) $activedesc = $('#gallerydesc ul li:last');

        var $next =  $active.next().length ? $active.next() : $('#gallerycycle ul li:first');
        var $nextdesc = $activedesc.next().length ? $activedesc.next() : $('#gallerydesc ul li:first');

        $active.addClass('last-active');
        $activedesc.addClass('last-active');

        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 0, function() {
                $active.removeClass('active last-active');
                $active.animate({opacity: 0.0}, 0);
                // run slideshow
                var _currentid = setInterval(initSlideshow, 5000 ); _playcontrol.attr('rel', _currentid);
        }),
        $nextdesc.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 0, function(){
                $activedesc.removeClass('active last-active');
                $activedesc.animate({opacity: 0.0}, 0);
        });

       return false;
    });

    // Pause Button
    _pause.click(function(){
       // swap buttons
       $(this).removeClass('active'),
       _play.addClass('active');

       // pause slideshow
       var _currentid = _playcontrol.attr('rel'); clearInterval(_currentid);

       return false;
    });

    // Play Button
    _play.click(function(){
       // swap buttons
       $(this).removeClass('active'),
       _pause.addClass('active');

       // run slideshow
       var _currentid = setInterval(initSlideshow, 5000 ); _playcontrol.attr('rel', _currentid);
       
       return false;
    });
}