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, " "));
}

function initMobile()
{
   var $viewfull = (typeof getParameterByName("viewfull") != "undefined") ? "true" : "false";
   if ($viewfull == "true")
   {
      setCookie("mc2_mobile","no",7,"/","","");
      var $mcookie = "no";
   }
   else
   {
      var $mcookie = getCookie("mc2_mobile");
   }
   var $ismobile = (typeof $mcookie != "undefined") ? ($mcookie == "no" ? "no" : "yes") : "yes";
   if(screen.width < 700 && $ismobile == "yes") {setCookie("mc2_mobile","yes",7,"/","","");document.location = "http://mobi.barclayagency.com/";}
}

//initMobile();




function getCookie( check_name ) {
   // first we'll split this cookie up into name/value pairs
   // document.cookie only returns name=value, not the other components
   var a_all_cookies = document.cookie.split( ';' );
   var a_temp_cookie = '';
   var cookie_name = '';
   var cookie_value = '';
   var b_cookie_found = false;
   var newcookie = '';

   for ( i = 0; i < a_all_cookies.length; i++ )
   {
      // splits apart each name=value pair
      a_temp_cookie = a_all_cookies[i].split( '=' );


      // and trims whitespace on the left and right of the value
      cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

      // if the cookie name matches the requested cookie
      if ( cookie_name == check_name )
      {
         b_cookie_found = true;
         // check whether found cookie has no value so we can return null if neccesary
         if ( a_temp_cookie.length > 1 )
         {
            cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
         }
         // return the cookie and stop script if value exists, otherwise, continue
         return cookie_value;
         break;
      }
      a_temp_cookie = null;
      cookie_name = '';
   }
   if ( !b_cookie_found )
   {
      return null;
   }
}


// SET COOKIE
function setCookie( name, value, expires, path, domain, secure )
{
   var valueexists = false;
   var value = escape(value);

   // check if cookie already exists so we can append value if neccesary
   existingcookie = getCookie( name );
   if ( existingcookie != null )
   {
      // split existingcookie up to an array and check if value exists
      cookiearray = existingcookie.split(',');
      for ( i = 0; i < 10; i++ )
      {
         if ( cookiearray[i] == unescape(value) )
         {
            valueexists = true;
         }
      } // end for loop

      // if value exists dont append cookie
      if ( valueexists == true )
      {
         return null
      } else { // otherwise append cookie to 9 most recent records
         for ( i = 0; i < 9; i++ )
         {
            if (cookiearray[i] != null) {
               value =  value + "," + cookiearray[i];
            }
         }
      }

   } else {

      value = unescape(value);
   }

   // sets time in milliseconds
   var today = new Date();
   today.setTime( today.getTime() );

   /*
if the expires variable is set, make the correct
expiration time, the current script below will set
it for x number of days,
delete * 24 to make it hours, delete * 60 * 24 to make it minutes
*/
   if ( expires )
   {
      expires = expires * 1000 * 60 * 60 * 24;
   }
   var expires_date = new Date( today.getTime() + (expires) );
   document.cookie = name + "=" + value +
   ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
   ( ( path ) ? ";path=" + path : "" ) +
   ( ( domain ) ? ";domain=" + domain : "" ) +
   ( ( secure ) ? ";secure" : "" );
}

// mc2.custom.recentspeakers.js
function getrecentSpeakers()
{
   // @todo use JSON object in speaker cookie to store speaker url and speaker name
   // Setting up the variables
   //var recentspeakerarray;
   //var recentspeakernamearray;

   // Get the cookie arrays
   recentspeakerurl = getCookie('recentspeaker');
   recentspeakername = getCookie('recentspeakername');
   speaker_html = '';

   // Check to ensure cookie values exist before looping
   if (recentspeakername != null)
   {
      speakername_array = recentspeakername.split(',');
      speakerurl_array = recentspeakerurl.split(',');
      // Loops through each speaker where 'i < x' AND 'i < total speakers in cookie'
      for ( i = 0; i < speakername_array.length && i < 10; i++ )
      {
         // Build HTML for recent speaker list in the following format: <li><a href="#">Alexander McCall Smith</a></li>
         speaker_html = speaker_html + '\n<li><a href="/' + speakerurl_array[i] + '.html">' + speakername_array[i] + '</a></li>';
      }
   }

   // Return the completed HTML
   return speaker_html;
}

















$(function(){
   initUniversalFunctions();
   initCarousel();
   initLightbox();
   initNoteworthy();
   initTitles();
   initHorizontalScroller();
   initIE();
   initBookshelf();
});

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
          rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

function initLightbox()
{
    var $version = getInternetExplorerVersion();
    var s = $("a.thickbox");
    var p = $("a.mobilepopup");

    if($version >= 7.0)
    {
        s.colorbox({
            iframe: true,
            fixed: true,
            width: 535,  // 535
            height: 572 // 535
        });
    } else {
        s.colorbox({
            iframe: true,
            fixed: true,
            width: 535,  // 535
            height: 535 // 535
        });
    }

    p.each(function(){
       $(this).attr("target","_blank");
    });
}

function initUniversalFunctions()
{
    $("a.noclick").click(function(){
        return false;
    })
}

function initIE()
{
    var i;
    for (i in document.images) {
        if (document.images[i].src) {
            var imgSrc = document.images[i].src;
            if (imgSrc.substr(imgSrc.length-4) === '.png' || imgSrc.substr(imgSrc.length-4) === '.PNG') {
                document.images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + imgSrc + "')";
            }
        }
    }
}

function initBookshelf()
{
   var $version = getInternetExplorerVersion();

   if($version == 7.0)
   {
      $(".books li").hover(
         function(){
            $(".books li div").stop(true,true).hide();
            $(this).addClass("active").find("div").css("filter", "progid:DXImageTransform.Microsoft.Fade(Duration=0.400, Overlap=0.0, Percent=100").css("background", "#efefef");
         }),
         function()
         {
            $(".books li div").hide();
            $(this).removeClass("active");
         }

   }
   else
   {

      $(".books li").hover( // hover state for books
           function(){
                   $(".books li div").stop(true,true).hide();
                   $(this).addClass("active").find("div").hide().fadeIn(450);
           },
           function(){
                   $(".books li div").hide();
                   $(this).removeClass("active");
           }
       );

   }
        // @todo add OE fade om ;pgoc
        // f($version >= 8.0) { $(this).find("img").css("filter", "progid:DXImageTransform.Microsoft.Fade(Duration=0.200, Overlap=0.0, Percent=0").css("background", "#eee"); }
}

function initHorizontalScroller()
{
    var _controls = $(".prevtitle, .nexttitle");
    var _s = $("#bookcarousel .books"); // selector

    var _eachoffset = $("#bookcarousel").width();
    var _left = 0;
    var _flagged = false;
    var _animation = 'easeOutCubic';
    var _ms = 1000;

    var _swidth = 0;
    $("#bookcarousel ul li").each(function(){
        _swidth = _swidth + $(this).outerWidth();
    })
    _s.css("width", _swidth);

    if(_swidth > _eachoffset+10)
    {
        // CREATE CLICK SELECTOR
        _controls.click(function()
        {
            // original left logic
            //        _left = ($(this).hasClass("prev-provider")) ? ((_left+_eachoffset >= 0) ? 0 : (_left+_eachoffset)) : ((_left-_eachoffset <= _swidth*-1) ? _left : (_left-_eachoffset));

            _flagged = false;
            if($(this).hasClass("prevtitle"))
            {
                // IS PREV
                if(_left+_eachoffset > 0)
                {
                    _left = 0;
                    _templeft = _left+50;
                    _flagged = true;
                    // hide prev arrow
                } else {
                    _left = _left+_eachoffset;
                }

            } else {
                // IS NEXT
                if(_left-_eachoffset <= _swidth*-1)
                {
                    // left doesnt change
                    // hide next arrow
                    _templeft = _left-50;
                    _flagged = true;

                } else {
                    _left = _left-_eachoffset;
                }
            }

            if(_flagged === true)
            {
                // show user we're at the end of the slides by faking the animation and animating back'
                _s.animate({
                    "left" : _templeft
                  }, {
                    duration: 250,
                    specialEasing: {
                      left: _animation
                    },
                    complete: function() {
                          _s.animate({
                            "left" : _left
                          }, {
                            duration: 650,
                            specialEasing: {
                              left: _animation
                            }
                          }); // end animation
                    }
                  }); // end animation





            } else {
                // default slide action
                _s.animate({
                    "left" : _left
                  }, {
                    duration: _ms,
                    specialEasing: {
                      left: _animation
                    }
                  });
            }
            return false; // kill default behavior for link click
        }).show();
    }

}

function initCarousel() {

    var settings = {};

//    carousel unique name
    settings['name']                    =   'slideshow';

//    elements
    settings['selector']                =   '#animatedcarousel li';
    settings['slide_selector_class']    =   ''; // only apply to selectors with the provided class
    settings['desc_selector']           =   '';

//    default settings
    settings['autoplay']                =   true;
    settings['slide_timing']            =   5000; // slide display timer in milliseconds
    settings['enable_controls']         =   true;

//    button controls
    settings['prev_btn']                =   'a.back-button';
    settings['next_btn']                =   'a.next-button';
    settings['play_btn']                =   'a.play-button';
    settings['pause_btn']               =   'a.pause-button';

//    transition controls
    settings['effect_transition']       =   'fade'; // transition effect
    settings['effect_timing']           =   1500; // fade transition in milliseconds

//    active / last-active classes
    settings['active_class']            =   'active'; // don't forget to set the first element to opacity 0 by default
    settings['lastactive_class']        =   'last-active';

    slideshow = new mc2Carousel(settings, _cb = function(){
       var url = $("#animatedcarousel li.active a").attr("href");
       $("#viewspeakerbtn").attr("href", url);
    });
}

function initNoteworthy() {

    var settings = {};

//    carousel unique name
    settings['name']                    =   'noteworthy';

//    elements
    settings['selector']                =   '#noteworthy .nwitem';
    settings['slide_selector_class']    =   ''; // only apply to selectors with the provided class
    settings['desc_selector']           =   '';

//    default settings
    settings['autoplay']                =   true;
    settings['slide_timing']            =   25000; // slide display timer in milliseconds
    settings['enable_controls']         =   false;

//    button controls
    settings['prev_btn']                =   '';
    settings['next_btn']                =   '';
    settings['play_btn']                =   '';
    settings['pause_btn']               =   '';

//    transition controls
    settings['effect_transition']       =   'fade'; // transition effect
    settings['effect_timing']           =   1200; // fade transition in milliseconds

//    active / last-active classes
    settings['active_class']            =   'active'; // don't forget to set the first element to opacity 0 by default
    settings['lastactive_class']        =   'last-active';

    var noteworthy = new mc2Carousel(settings, _cb = function(){
       var h = $(".nwitem.active").find("div").outerHeight();
       $("#noteworthy").animate({height: h}, 1000);
    });
}

function initTitles() {

   if($(".titles .sidebarthumb").length)
   {
    var settings = {};

//    carousel unique name
    settings['name']                    =   'titles';

//    elements
    settings['selector']                =   '.titles .sidebarthumb';
    settings['slide_selector_class']    =   ''; // only apply to selectors with the provided class
    settings['desc_selector']           =   '';

//    default settings
    settings['autoplay']                =   true;
    settings['slide_timing']            =   5000; // slide display timer in milliseconds
    settings['enable_controls']         =   false;

//    button controls
    settings['prev_btn']                =   '';
    settings['next_btn']                =   '';
    settings['play_btn']                =   '';
    settings['pause_btn']               =   '';

//    transition controls
    settings['effect_transition']       =   'fade'; // transition effect
    settings['effect_timing']           =   1500; // fade transition in milliseconds

//    active / last-active classes
    settings['active_class']            =   'active'; // don't forget to set the first element to opacity 0 by default
    settings['lastactive_class']        =   'last-active';

    titles = new mc2Carousel(settings);
   }

}


function mc2Carousel(settings, _cb)
{
    var settings2 = settings;
    var name = settings.name;

    if(settings.name == "slideshow" && $(settings.selector).length)
    {
        var _url = "/index.php/json/carousel";

        $.getJSON(_url, function (d)
        {
            if(typeof d == "object")
            {
                speakerdata = d.results[0];
                var _output = "";

                $.each(speakerdata, function(i,val)
                {
                   // preload images
                });
            }
        });
    }

    function processCarousel(settings, _cb)
    {
        var $active = ($(settings.selector+'.'+settings.active_class).length !== 0) ? $(settings.selector+'.'+settings.active_class) : $(settings.selector+':last');
        var $next     = $active.next().length ? $active.next() : $(settings.selector+':first');

        $active.addClass(settings.lastactive_class);

        $next.css({opacity: 0.0})
            .addClass(settings.active_class)
            .animate({opacity: 1.0}, settings.effect_timing),

        $active.removeClass(settings.active_class+' '+settings.lastactive_class),
        $active.animate({opacity: 0.0}, settings.effect_timing);

        if(typeof _cb != "undefined") {this._cb();}
    } // end process Carousel

    if ($(settings.selector).length > 1) // run Carousel only if there is more than 1 element to carousel through
    {
         settings.name = setInterval(function(){processCarousel(settings, _cb)}, settings.slide_timing);
    }
    /**
     *      CONTROLS
     */

    if(settings.enable_controls == true)
    {
        if ($(settings.selector).length > 1)
        {
            $(settings.next_btn).unbind();
            $(settings.prev_btn).unbind();
            $(settings.play_btn).unbind();
            $(settings.pause_btn).unbind();
        }
        $(settings.next_btn).click(function()
        {
            if (typeof $active != "undefined") $active.stop(true,true);
            if (typeof $next != "undefined") $next.stop(true,true);
            clearInterval(settings.name);
            $active = $(settings.selector+'.'+settings.active_class).length ? $(settings.selector+'.'+settings.active_class) : $(settings.selector+":first");
            $next = ($active.next().length) ? $active.next() : $(settings.selector+":first");
            $next.css({opacity: 0.0}).addClass(settings.active_class).animate({opacity: 1.0}, 400),
            $active.removeClass(settings.active_class+' '+settings.lastactive_class),
            $active.animate({opacity: 0.0}, 400);
            $(settings.pause_btn).fadeOut(300, function(){$(settings.play_btn).fadeIn(200);});

            var _index = $next.index();
            return false;
        });
        $(settings.prev_btn).click(function()
        {
            if (typeof $active != "undefined") $active.stop(true,true);
            if (typeof $next != "undefined") $next.stop(true,true);
            clearInterval(settings.name);
            $active = $(settings.selector+'.'+settings.active_class).length ? $(settings.selector+'.'+settings.active_class) : $(settings.selector+":first");
            $next = ($active.prev().length) ? $active.prev() : $(settings.selector+":last");
            $next.css({opacity: 0.0}).addClass(settings.active_class).animate({opacity: 1.0}, 400),
            $active.removeClass(settings.active_class+' '+settings.lastactive_class),
            $active.animate({opacity: 0.0}, 400);
            return false;
        });
        $(settings.play_btn).click(function()
        {
            settings.name = setInterval(function(){processCarousel(settings);}, settings.slide_timing);
            $(this).fadeOut(300, function(){$(settings.pause_btn).fadeIn(200);});
            return false;
        });

        $(settings.pause_btn).click(function()
        {
            clearInterval(settings.name);
            $(this).fadeOut(300, function(){$(settings.play_btn).fadeIn(200);});
            return false;
        });
    }



}
