/**
*	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();
    //initSubnavigation();
    initColorbox();
//    initBrowsercheck();
    initGalleryScroll();
    imageStatus();
    navigationEvents();
    showNavigation();
    initLogging();
});

function initGalleryScroll()
{
    $('div.G1').galleryScroll();
}

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 initBrowsercheck()
{
    var ua = navigator.userAgent.toLowerCase();
    var client = {
        isStrict:   document.compatMode == 'CSS1Compat',
        isOpera:    ua.indexOf('opera') > -1,
        isIE:       ua.indexOf('msie') > -1,
        isIE7:      ua.indexOf('msie 7') > -1,
        isSafari:   /webkit|khtml/.test(ua),
        isWindows:  ua.indexOf('windows') != -1 || ua.indexOf('win32') != -1,
        isMac:      ua.indexOf('macintosh') != -1 || ua.indexOf('mac os x') != -1,
        isLinux:    ua.indexOf('linux') != -1
    };
    client.isBorderBox = client.isIE && !client.isStrict;
    client.isSafari3 = client.isSafari && !!(document.evaluate);
    client.isGecko = ua.indexOf('gecko') != -1 && !client.isSafari;

    /**
     * You're not still using IE6, are you?
     *
     * @var         Boolean
     * @private
     */
    var ltIE7 = client.isIE && !client.isIE7;

    if(ltIE7){
      addLoadEvent(display_warning);
    }

    function addLoadEvent(func)
    {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
              func();
              if (oldonload) {
                oldonload();
              }
            }
        }
    }

    function display_warning()
    {
        var oldHtml = document.body.innerHTML;
        var css_a = 'text-decoration: underline; color: black; font-weight:bold;';
        var warningHtml = "";
        warningHtml += '<style>';
        warningHtml += 'html, body { ';
        warningHtml += 'overflow-y: hidden!important; ';
        warningHtml += 'height: 100%;';
        warningHtml += 'padding: 0px;';
        warningHtml += 'margin: 0px;';
        warningHtml += '</style>';
        warningHtml += "<div style='position: absolute; top:0px; bottom:auto; left:0px; right:0px; margin: 0px; height:17px; padding: 3px; font-family: Verdana, Helvetica, Geneva, Arial, sans-serif; font-size:10px; background-color:#FFFFE1; color:black; border-top: 1px solid #FFFFE1; border-bottom: 1px solid #cccccc; padding-left:15px; margin-left: -15px;'>";
        warningHtml += "<div style='float:right; text-align:right; width:60px; margin: auto 5px;'>";
        warningHtml += "<a style='text-decoration: none; color: black;' href='#close' onclick='this.parentNode.parentNode.style.display=\"none\"; this.parentNode.parentNode.parentNode.childNodes[0].childNodes[0].style.display=\"none\"; return false;'>[ close ]</a>";
        warningHtml += "</div>";
        warningHtml += "<div style='text-align:left; margin:auto 10px;'>";
        warningHtml += "You are using an unsupported version of Internet Explorer, <a style='"+css_a+"' target='_blank' href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx'>click here</a> to download the latest version! For optimum performance and security, we recommend <a style='"+css_a+"' target='_blank' href='http://www.mozilla.com/firefox/'>Firefox</a> or <a style='"+css_a+"' target='_blank' href='http://www.google.com/chrome'>Google Chrome</a>.";
        warningHtml += "</div>";
        warningHtml += "</div>";
        var spacerHTML = "";
        spacerHTML += "<div style='height:25px; line-height:25px; font-size:10px; display:block; margin:0px; padding:0px;'>";
        spacerHTML += "</div>";
        var oldHTMLWrap = "";
        oldHTMLWrap += "<div style='width:100%; margin:0px; padding:0px; height:100%; overflow-y: scroll; position:relative;'>";
        oldHTMLWrap += spacerHTML;
        oldHTMLWrap += oldHtml;
        oldHTMLWrap += "</div>";
        document.body.innerHTML = oldHTMLWrap + warningHtml;
    }
}

function initColorbox()
{
                $("a.lightbox").colorbox({maxHeight:'85%',maxWidth:'85%'});
}

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

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 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 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 initSubnavigation()
{
    var _subpages = $('div.twocolumns');
    var _subnavitem = $("li.sub-level-1 a");

    // BEGIN CLICK EVENT
    _subnavitem.click(function(){

        // stop existing animations
        _subpages.stop(false,true);
        // make navigation show "selected" state
        $("li.sub-level-1").removeClass('active'),
        $(this).parent().addClass('active');

        // content variables
        var _identifier     = $('div.' + $(this).attr('rel'));
        var _currentactive  = $('div.subactive');
        var _summarytext    = $('.text-block .text-holder');
        var _summaryimg     = $('.text-block img.alignright');

            // hide landing page text and image
            _summarytext.fadeOut(300);
            _summaryimg.slideUp(1000, function(){
                // hide landing page text/image if neccesary, slide-hide any showing content and slide-show requested content
                if(_subpages.hasClass('subactive')) {
                    _currentactive.fadeOut(500,function(){
                        _subpages.removeClass('subactive');
                        _identifier.fadeIn(1000, function(){
                            _identifier.addClass('subactive');
                        }); // end slideDown
                    });
                } else {
                    _identifier.fadeIn(1000, function(){
                        _identifier.addClass('subactive');
                    }); // end _identifier.slideDown()
                }
            }); // end _summaryimg.slideUp()

        return false;
    }); // END CLICK EVENT

} // end initSubnavigation()


function imageStatus(){

    var img = document.getElementById("firstgallery");

    if(img) {
        var imagestatus = setInterval(
                    function()
                    {
                        $.console('imagecheck');
                      if(img.complete)
                      {
                        clearInterval(imagestatus);
                        preloadImages();
                        showNavigation();
                      }
                    },
                    50);
    }
}

function preloadImages()
{
    var _eid = $("#galleryimage1").attr("data-eid");
    var _url = '/json/_carousel/'+_eid+'/';

    $.getJSON(_url, function(data){
        var _images = data.results[0];
        var _img;

        $.each(_images, function(i, val){
            _img = $("<img />").attr("src", val);
            $("#galleryimage"+i).html(_img);

        });
    });
}

function showNavigation()
{
    $("div.holder, .link-prev, .link-next").removeClass("hide");
}

function navigationEvents()
{
    $("div.holder, .link-prev, .link-next").hover(function(){
        if($(this).hasClass("holder"))
        {
            $(".link-prev, .link-next, .holder .text").stop(true,true).fadeIn(400);
        } else {
            $(this).stop(true,true).show();
        }

    }, function(){
        $(".link-prev, .link-next, .holder .text").stop(true,true).fadeOut(400);
    });
}

/**
 *      INITLOGGING
 *      Notes: Only console.logs if the console object exists. Very useful for debugging without breaking
 *      site functionality in Internet Explorer and browsers that don't have the console object by default.
 */
function initLogging()
{
    jQuery.console = function(text){
        if( (window['console'] !== undefined) ){
            console.info(text);
        }
    }
}
