/********************************************************************************
 * CONTEXTURE JAVASCRIPT LIBRARY
 * This file contains default JavaScript code for use in most web applications. Generally, this file is named
 * "library.js"
 *
 * NOTE: When used with Wordpress, do not use the dollar sign ($) shortcut for jQuery expressions. Instead,
 * spell out "jQuery". For example: jQuery('selector')
  ********************************************************************************/

/********************************************************************************
 * ctxGlobals Object
  *
 * PURPOSE: Used to store some basic (mostly dynamic) global data that may need to be reused throughout
 * an entire javascript application.
 ********************************************************************************/
var ctxGlobals = {
    /**0 = hide immediately. Try to animate this much DOM and most browsers will die*/
    slideSpeed: 0,
    /**Gets the uri of the current webpage to limit JS execution*/
    uri:        window.location.pathname,
    /**Returns a string formatted with todays date as m/-/d/-/yyyy*/
    today:      function(){var now = new Date();return (now.getMonth()+1)+"/"+now.getDate()+"/"+now.getFullYear()},
    /**The current page anchor value */
    anchor:     unescape(document.location.hash.substring(1)),
    /**What device is the user using? */
    deviceid:    navigator.userAgent.toLowerCase(),
    /**True if device is an iPhone*/
    isiphone:   (navigator.userAgent.toLowerCase().indexOf('iphone')!='-1'),
    /**True if device is an iPad*/
    isipad:     (navigator.userAgent.toLowerCase().indexOf('ipad')!='-1'),
    /**True if device is Android*/
    isandroid:  (navigator.userAgent.toLowerCase().indexOf('android')!='-1')
}

/********************************************************************************
 * !NOFUNC!
 * PURPOSE: If firebug isn't loaded on the client's browser, this ensures that any residual
 * console.log statements left in the js code won't break the javascript. It serves no
 * other purpose than to prevent errors by ensuring these objects exist without firebug.
 ********************************************************************************/
if(!window.console){window.console=new function(){this.log=function(str){};this.dir=function(str){}}};


/********************************************************************************
 * !NOFUNC!
 * PURPOSE: Test if jQuery is already loaded and load it from Google code if it isn't
 * (this should be the first thing in this file).
 ********************************************************************************/
if(typeof(jQuery)=='undefined'){
    var loadjQuery = document.createElement("script");
    loadjQuery.setAttribute("type","text/javascript");
    loadjQuery.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js");
    document.getElementsByTagName("head")[0].appendChild(loadjQuery);
}


/********************************************************************************
 * jQuery.exists()
 * PURPOSE: Simple jQuery function to check if a selector exists ( if(object.exists()){} )
 ********************************************************************************/
jQuery.fn.exists = function(){return jQuery(this).length>0;}

/********************************************************************************
 * jQuery.nextOrFirst()
 * PURPOSE: Works like next(), except gets the first item of a group of siblings
 * if there is no next sibling to get.
 ********************************************************************************/
jQuery.fn.nextOrFirst = function(){
    if(jQuery(this).next().length === 0){
        return jQuery(this).parent().children(':first');
    }else{
        return jQuery(this).next();
    }
}


/********************************************************************************
 * jQuery.trim()
 * PURPOSE: Trims the leading/trailing white space from a string.
 ********************************************************************************/
jQuery.fn.trim = function(){
    return jQuery(this).val().replace(/^\s+|\s+$/g, '');
}


/********************************************************************************
 * jQuery.selectTab()
 *
 * PURPOSE: Simple jQuery function to handling quick-n-dirty tabination. Simply attach the function to any
 * jQuery selection/object that needs to act as the TAB and pass in a second jQuery selector for the tab
 * CONTENT. Please note that both the TABS and CONTENT need to be in their own containers, or this could
 * cause severe wonkiness (as it makes use of siblings).
 *
 * CSS:
 * -"active" - the tab that is currently ACTIVE (whose content is being shown)
 ********************************************************************************/
jQuery.fn.selectTab = function(jqselect,callback){
  jQuery(this).click(function(){ //Click event (automatic)
    if(jQuery(this).hasClass('cattab')){
        jQuery('.tabs-2-frame td').removeClass('active'); //We do this to avoid animation breaks on webPortfolioSwipe() when clicking an already-active tab
    }
    jQuery(this).siblings().removeClass('active').end().addClass('active'); //Ensure this element is the only one with the active class
    jQuery(jqselect).siblings(':visible').stop(false,true).fadeOut(500,function(){ //Fade out currently visible item
        jQuery('.tabs-video').css({'display':'none','margin-right':'-900px'});
        jQuery(jqselect).stop(false,true).fadeIn(500);
        jQuery(jqselect).find('.tabs-video').css('display','block').animate({'margin-right':'0'},500);
    })
    if(callback != null && typeof callback === 'function'){
        callback();
    }
  });
}

/********************************************************************************
 * jQuery.UrlGET()
 * PURPOSE: This handy jQuery function that allows you to GET parameters from the querystring.
 * It can be used very simply like so: var pageid = jQuery(document).UrlGET('pageid');
 ********************************************************************************/
jQuery.fn.extend({UrlGET: function (strParamName) {
        strParamName = escape(unescape(strParamName));
        var returnVal = new Array();
        var qString = null;
        if (jQuery(this).attr("nodeName") == "#document") {
            if (window.location.search.search(strParamName) > -1) {
                qString = window.location.search.substr(1, window.location.search.length).split("&");
            }
        } else {
            if (jQuery(this).attr("src") != "undefined") {
                var strHref = jQuery(this).attr("src");
                if (strHref.indexOf("?") > -1) {
                    var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
                    qString = strQueryString.split("&");
                }
            } else {
                if (jQuery(this).attr("href") != "undefined") {
                    var strHref = jQuery(this).attr("href");
                    if (strHref.indexOf("?") > -1) {
                        var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
                        qString = strQueryString.split("&");
                    }
                } else {
                    return null;
                }
            }
        }
        if (qString == null) {
            return null;
        }
        for (var i = 0; i < qString.length; i++) {
            if (escape(unescape(qString[i].split("=")[0])) == strParamName) {
                returnVal.push(qString[i].split("=")[1]);
            }
        }if (returnVal.length == 0) {
            return null;
        } else {
            if (returnVal.length == 1) {
                return returnVal[0];
            } else {
                return returnVal;
            }
        }
    }
});


/********************************************************************************
 * jQuery CooQuery Plugin v2 (minified) - http://cooquery.lenonmarcel.com.br/
 * Creates, sets, and deletes cookies.
 *
 * //CREATE/SET A COOKIE:
 * jQuery.setCookie( 'NAME', 'VALUE', {
 *     duration : 1, // In days
 *     path : '',
 *     domain : '',
 *     secure : false
 * });
 *
 * //READ A COOKIE VALUE:
 * jQuery.getCookie( 'NAME' );
 *
 * //DELETE A COOKIE:
 * jQuery.delCookie( 'NAME' );
 ********************************************************************************/
(function(jQuery){
  /**
   * Sets a cookie.
   * @param string name The name of the cookie.
   * @param string value The value of the cookie
   * @param hash options Options to set for this cookie
   * @option int duration
   * @option string path
   * @option string domain
   * @option boolean secure
   * @returns Returns false if there's a problem, else returns the cookie.
   */
  jQuery.setCookie = function( name, value, options ){
    if( typeof name === 'undefined' || typeof value === 'undefined' )
      return false;

    var str = name + '=' + encodeURIComponent(value);

    if( options.domain ) str += '; domain=' + options.domain;
    if( options.path ) str += '; path=' + options.path;
    if( options.duration ){
      var date = new Date();
      date.setTime( date.getTime() + options.duration * 24 * 60 * 60 * 1000 );
      str += '; expires=' + date.toGMTString();
    }
    if( options.secure ) str += '; secure';

    return document.cookie = str;
  };
  /**
   * Deletes a cookie by resetting it as expired.
   * @param string name The name of the cookie to delete.
   * @returns Returns false if there's a problem, else returns the cookie.
   */
  jQuery.delCookie = function( name ){
    return jQuery.setCookie( name, '', {duration: -1} );
  };

/**
   * Gets a cookie value.
   * @param string name The name of the cookie.
   * @returns Returns false if there's a problem, else returns the cookie value.
   */
  jQuery.getCookie = function( name ){
    var value = document.cookie.match('(?:^|;)\\s*' + name.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1') + '=([^;]*)');
    return (value) ? decodeURIComponent(value[1]) : null;
  };

})(jQuery);

/********************************************************************************
 * addFlashVid()
 *
 * PURPOSE:
 * This will generate full HTML for a flv video. You must have the source files placed in
 * a media folder relative to the current location of the webpage. This includes
 * play-button.png, the poster frame, the flv, the player (FLVPlayer_Progressive.swf),
 * and the skin (clearSkin_3.swf). To use this, simple call the function within one
 * of jQuery DOM-manupulation methods, such as append() or after().
 *
 * @param string strPlayerID Define a unique id for this video player.
 * @param string strVidURL The URL (root relative) of the FLV to load, DO NOT include the .flv extension (ie: myvideofilename)
 * @param string strPostFrURL The URL and filename (with extension) of the image to use as a poster frame (ie: media/postframe.jpg). Enter blank '' to not use posterframe.
 * @param int iWidth The width (in px) of the video/poster frame.
 * @param int iHeight The height (in px) of the video/poster frame (do not include px at end).
 * @return string Returns the generated HTML for the flash player (do not include px at end).
 *********************************************************************************/
function addFlashVid(strPlayerID,strVidURL,strPostFrURL,iWidth,iHeight){

    var myDisplay = 'none';
    var btnDisplay = 'block';
    //Base URL for player assets (FLVPlayer_Progressive.swf, clearSkin_3.swf, play-button.png)
    var strBaseURL = '/media/';
    //Vertically centers the play button based on the height of the video
    var iPadding = (iHeight/2)-40;
    //Determine whether or not the video loads immediately (depends on if we're using a poster frame)
    if(strPostFrURL==''){myDisplay='block';btnDisplay='none'}

    //Build basic returnHTMLregardless of whether we use a poster frame or not
    var returnHTML = '\
            <div id="'+strPlayerID+'-video" style="display:'+myDisplay+';">\
                <object id="FLVPlayer" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="'+iHeight+'" width="'+iWidth+'">\
                    <param name="salign" value="lt"><param name="quality" value="high"><param name="scale" value="noscale"><param name="wmode" value="transparent">\
                    <param name="src" value="'+strBaseURL+'FLVPlayer_Progressive.swf">\
                    <param name="name" value="FLVPlayer">\
                    <param name="flashvars" value="&amp;skinName='+strBaseURL+'clearSkin_3&amp;streamName='+strVidURL+'&amp;autoPlay=true&amp;autoRewind=false">\
                    <embed id="'+strPlayerID+'-FLVPlayer" type="application/x-shockwave-flash" src="'+strBaseURL+'FLVPlayer_Progressive.swf" name="FLVPlayer" flashvars="&amp;skinName='+strBaseURL+'clearSkin_3&amp;streamName='+strVidURL+'&amp;autoPlay=true&amp;autoRewind=true" wmode="transparent" scale="noscale" quality="high" salign="lt" height="'+iHeight+'" width="'+iWidth+'">\
                </object>\
            </div>';

   //If a poster frame is defined (NOT ''), then add the poster frame code
   if(strPostFrURL!=''){
       returnHTML='\
            <div id="'+strPlayerID+'" style="width:'+iWidth+'px;height:'+iHeight+'px;margin-left:auto;margin-right:auto;background-color:black;cursor:pointer;">\
            <p id="'+strPlayerID+'-poster" style="padding:0;padding-top:'+iPadding+'px;margin:0;width:'+iWidth+'px;height:'+(iHeight-iPadding)+'px;background:url('+strPostFrURL+') no-repeat center center;">\
                <img src="'+strBaseURL+'play-button.png" width="76" height="59" style="display:'+btnDisplay+';margin-left:auto;margin-right:auto;" onload="jQuery(this).fadeTo(300,0.5);" />\
            </p>\
            '+returnHTML+
            '</div>';
   }

   //Append the Javascript controls to the video
   returnHTML += '\
        <scr'+'ipt type="text/javascript">\n\
            jQuery("#'+strPlayerID+'").hover(function(){\n\
                    jQuery("#'+strPlayerID+'-poster img").stop().fadeTo(300,1);\n\
                },function(){\n\
                    jQuery("#'+strPlayerID+'-poster img").stop().fadeTo(300,0.5);\n\
            }).click(function(){\n\
                jQuery("#'+strPlayerID+'-poster").stop().fadeOut(function(){\n\
                    jQuery("#'+strPlayerID+'-video").show();\n\
                });\n\
            });\n\
        </scr'+'ipt>\
    ';
    return returnHTML;
}


/********************************************************************************
 * animateQuotes()
 *
 * PURPOSE:
 * Controls animation of the quote box on the front page.
 *********************************************************************************/
function animateQuotes(){
    jQuery('#quote-spinner .fp-quote') //Get all quotes
        .filter(':hidden:first').show().animate({opacity:'1.0'},1200).end() //Get the first hidden quote and show it. Go back.
        .filter(':visible:first').animate({'margin-top':'-90px',opacity:'-0'},1000, //Get first visible quote, animate it's top margins to -190px
            function(){ //When that's done...
                jQuery(this).hide() //Hide it
                .css({'margin-top':'0'}) //Set the top margin back to normal
                .insertAfter('#quote-spinner .fp-quote:last'); //Move it to the end of the quote list
                setTimeout('animateQuotes()',5000); //Wait 5 seconds and do this again
            });
}


/********************************************************************************
 * jQuery.webPortfolioSwipe()
 *
 * PURPOSE:
 * Controls "sweeping" animation of items on the Web portfolio page
 *********************************************************************************/
jQuery.fn.webPortfolioSwipe = function(copyselector,imgselector,speed){
    if(speed===null){speed=1000;}
    jQuery(this).click(function(){
        var tcont = jQuery('#tabs-content');
        var tcopy = jQuery('#tabs-content-text');
        var timgs = jQuery('#tabs-content-imgs');
        var newimg = jQuery(imgselector);
        var newcpy = jQuery(copyselector);
        var halfspeed = speed / 2;

        //Only run the animation if it's not already the active one'
        //if(!jQuery(this).hasClass('active')){
            //Give current tab the active class
            jQuery(this).addClass('active').siblings().removeClass('active');
            //Slide OUT current img to the left
            timgs.find('.webimg.current').stop(true,true).animate({'left':'-960px'},speed,function(){
                jQuery(this).removeAttr('style').removeClass('current');
            });
            //Slide IN new image from the right
            newimg.stop(true,true).animate({'left':'0'},speed,function(){
                jQuery(this).addClass('current');
                jQuery(this).siblings().removeAttr('style').removeClass('current');
            });
            //Fade out old text, fade in new text
            tcopy.find('.webcopy').stop(true,true).filter(':visible').fadeOut(halfspeed,function(){
                newcpy.fadeIn(halfspeed);
            });
            //Adjust height of container to height of heigest element
            var newheight = (newimg.height() > newcpy.height()) ? newimg.height() : newcpy.height();
            tcont.stop(true,true).animate({'height':newheight+"px"},speed);
        //}
    });
}

/********************************************************************************
 * jQuery.ctxLB()
 *
 * PURPOSE:
 * Lets you create a lightbox willy-nilly whenever you please. The lightbox can be closed by clicking anywhere
 * in the "gray" area. The lightbox can be further customized via CSS (I recommend using a transparent png for
 * #ctx-lightbox's background instead of a solid color). Note that the html, body CSS specified below is
 * CRITICAL to this working.
 *
 * CSS:
 * html, body {height:100%;width:100%;}
 * body { padding:0;margin:0; }
 *
 *   #ctx-lightbox { background:gray;position:fixed;width:100%;height:100%;display:none; }
 *     #ctx-lightbox td { vertical-align:middle; }
 *     #ctx-lightbox-content {
 *        margin-left:auto;
 *        margin-right:auto;
 *        background:white;
 *        border:1px solid black;
 *        border-radius:5px;
 *        -webkit-border-radius:5px;
 *        -moz-border-radius:5px;
 *        box-shadow: black 0px 0px 50px;
 *        -webkit-box-shadow: black 0px 0px 50px;
 *        -moz-box-shadow: black 0px 0px 50px;
 *        width:50%;
 *        padding:10px;
 *     }
 *
 * EXAMPLE:
 * jQuery('#open-lightbox').ctxLB('Hello World!',500);
 ********************************************************************************/
jQuery.fn.ctxLB = function(content,speed){
  jQuery(this).click(function(){
    if(speed===null){speed=1000;}
    var ctxlbhtml = '<table id="ctx-lightbox" cellpadding="0" cellspacing="0"><tbody><tr><td><div id="ctx-lightbox-content">'+content+'</div></td></tr></tbody></table>';
    jQuery('body').prepend(ctxlbhtml);
    jQuery('#ctx-lightbox').show() //Unhide the div (it's still invisible due to opacity 0
    .css('height',jQuery(document).height()+'px') //Set the height of the thing to the height of the document
        .find('#ctx-lightbox-content')
            .css({'margin-top':((typeof(window.pageYOffset)=='number') ? window.pageYOffset : document.documentElement.scrollTop)})
            .end()
    .animate({'opacity':'1.0'},1000).click(function(){ //Animate FadeIn (manually)
      jQuery(this).fadeOut(1000,function(){
        jQuery(this).remove();
      });
    });
    jQuery('#ctx-lightbox-content').click(function(event){
      event.stopPropagation();
    });
    jQuery('.ctx-lb-close').click(function(){jQuery('#ctx-lightbox').click();});
    VimeoLovesiDevice();
  });
}

/**
 * Controls the cross-fade of the showcase area on the front page
 */
function rotateShowcase(){
    //console.log('Loop');

    jQuery('#showcase .sc-current').fadeOut(3000,function(){
        //console.log('FadeOut Callback');

        //Get rid of the display:none that FadeOut adds
        jQuery(this).removeAttr('style');


        //console.log('Next (after '+jQuery(this).attr('id')+')');
        jQuery(this).attr('class','sc-hidden') //Hide current
            .nextOrFirst().attr('class','sc-current') //Next becomes current
            .nextOrFirst().attr('class','sc-next'); //Next becomes next

    });
    setTimeout('rotateShowcase()',10000);
}

function VimeoLovesiDevice(){
    //If this is an iphone, replace video object with this code...
    if(ctxGlobals.isiphone || ctxGlobals.isipad || ctxGlobals.isandroid){
        var vidobj = jQuery('object param[name="movie"]');
        vidobj.each(function(){
          var vidid = jQuery(this).attr('value').match(/clip_id=(\d*)\&/)[1];
          var vidwidth = jQuery(this).parent().attr('width');
          var vidheight = jQuery(this).parent().attr('height');
          var mobileQual = ''; //Assume full quality for iPad

          if(!ctxGlobals.isipad){
              mobileQual = '&quality=mobile'; //Set to mobile quality if on small mobile
          }
          var vidlink = "<div><strong>Tap video box below to view the video on your mobile device.<strong></div><video src='http://www.vimeo.com/play_redirect?clip_id="+vidid+mobileQual+"' controls='controls' width='"+vidwidth+"' height='"+vidheight+"'></video>";
          jQuery(this).parent().after(vidlink);
          jQuery(this).parent().remove();
        });
    }
}
