/********************************************************************************
 * 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')
  ********************************************************************************/

/********************************************************************************
 * !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.trim()
 * PURPOSE: Trims the leading/trailing white space from a string.
 ********************************************************************************/
jQuery.fn.trim = function(){
    return jQuery(this).val().replace(/^\s+|\s+$/g, '');
}


/********************************************************************************
 * 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 = $(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:
 * $.setCookie( 'NAME', 'VALUE', {
 *     duration : 1, // In days
 *     path : '',
 *     domain : '',
 *     secure : false
 * });
 *
 * //READ A COOKIE VALUE:
 * $.getCookie( 'NAME' );
 *
 * //DELETE A COOKIE:
 * $.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 $.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);


/********************************************************************************
 * PaginateComments()
 * Creates a pagination control on the page. Four pieces are needed for this to work: a
 * scope element (with unique id), a container element that holds the elements to paginate (id),
 * a pagination control element OUTSIDE the container element (class), and individual "row" elements
 * within the container element (class). Like so...
 *
 * <div id="master-container">
 *   <div class="comment-pagination-control"/>
 *   <div id="comment-container">
 *     <div class="comment-row"></div>
 *     <div class="comment-row"></div>
 *     <div class="comment-row"></div>
 *   </div>
 *   <div class="comment-pagination-control"/>
 * </div>
 *
 * The master-container's id is passed into PaginateComments() as a parameter. So long as the other
 * elements have the correct ids and classes, everything is automatic.
 *
 * @param mstrcontid The id of the master container.
 ********************************************************************************/
function PaginateComments(mstrcontid){
    var iComPerPage = 15; //Change this value to set the number of comments that appear per page
    var objComments = jQuery('#comment-list-container .comment-row'); //Gets all the comments
    var iComments = objComments.length; //Count comments in this post
    var iPages = Math.ceil(iComments/iComPerPage); //Determine number of pages (rounded up) if we want 15 comments/page
    var iCurPage = parseInt(jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).filter(':eq(1)').attr('page')); //Gets the current page

    //SET INITIAL STATE
    jQuery('head').append('<style type=\"text/css\">#comment-list-container .comment-row { display:none; }</style>');
    var iStartPage=1; //Set default start page at page 1
    var iQueryPageId=parseInt(jQuery(document).UrlGET('commentpage')); //Get pagenum from querystring
    if(iQueryPageId===parseInt(iQueryPageId)){iStartPage=iQueryPageId;console.log(iStartPage);}
    jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).attr('page', iStartPage); //Set pagination to page 1 by adding an attribute to .comment-pagination-control
    for(i=0;i<iComPerPage;i++){ //Reveal only the posts for the first page
        objComments.filter(':eq('+i+')').show();
    }

    //BUILD THE PAGE CONTROL
    if(iPages>1){
        GeneratePageControl();
    }

    //Internal function for recursive purposes - generates the control bar and functionality
    function GeneratePageControl(){
        iCurPage = parseInt(jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).filter(':eq(1)').attr('page')); //Gets the current page
        var strPageButtons = '';
        if(iPages<=10){
            for (i = 1; i <= iPages; i++) { //When we have less than iMaxPages, show all pages
                if(i==iCurPage){
                    strPageButtons += "<span class=\"comment-page-button comment-page-num current-page\">"+i+"</span>";
                }else{
                    strPageButtons += "<span class=\"comment-page-button comment-page-num\">"+i+"</span>";
                }
            }
        }else{ //When we have MORE than iMaxPages, we split it so people know how many pages there are.
            console.log('Lotsa pages. CurPage:'+iCurPage+" TotPages:"+iPages);
            for (i = 1; i <= iPages; i++) {
                if(i==iCurPage){ //Renders and marks the current page
                    strPageButtons += "<span class=\"comment-page-button comment-page-num current-page\">"+i+"</span>";
                }else if(i>=(iCurPage-4) && i<=(iCurPage+4)){ //Renders current page +/-4
                    strPageButtons += "<span class=\"comment-page-button comment-page-num\">"+i+"</span>";
                }else if(i==(iPages-1)){ //Renders the "spacer" spot if we're near the end
                    strPageButtons += "<span class=\"comment-page-skip\">...</span>";
                }else if(i==iPages){ //Renders the last page
                    strPageButtons += "<span class=\"comment-page-button comment-page-num\">"+iPages+"</span>";
                }else{
                    //Do nothing
                }
            }
        }
        //We add the "static" buttons to the dynamic ones we generated above (First/Prev/Next/Last)
        strPageButtons="<span class=\"comment-page-title\">Page: </span><span class=\"comment-page-button first-page\">&lt; First</span><span class=\"comment-page-button prev-page\">&lt;&lt; Prev</span>"
            +strPageButtons+"<span class=\"comment-page-button next-page\">Next &gt;&gt;</span><span class=\"comment-page-button last-page\">Last &gt;</span>";
        jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).html('');//Clear out previous control
        jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).append(strPageButtons);//Add updated control

        //ADD FUNCTIONALITY TRIGGERS TO CONTROL
        jQuery('.comment-pagination-control .comment-page-button',jQuery('#'+mstrcontid)).each(function(){
            var objMe = jQuery(this);
            objMe.click(function(){ //What we do with each page button when it's clicked
                var strNewPage = parseInt(objMe.text()); //The new page is set to whatever the text of this button is (might be non-int)
                //Special behaviors for special buttons
                if(jQuery(this).hasClass('next-page')){ //If next page button, go to next page
                    if(parseInt(iCurPage)<iPages){strNewPage=iCurPage+1;} //But only if we're not on the last page
                    if(strNewPage!==parseInt(strNewPage)){strNewPage=iCurPage;} //If strNewPage isn't a valid page number, we use the current page
                }else if(jQuery(this).hasClass('prev-page')){//If prev page button, go to prev page
                    if(parseInt(iCurPage)>1){strNewPage=iCurPage-1;}//But only if we're not on the first page
                    if(strNewPage!==parseInt(strNewPage)){strNewPage=iCurPage;} //If strNewPage isn't a valid page number, we use the current page
                }else if(jQuery(this).hasClass('first-page')){//If first page button, go to first page
                    strNewPage=1;
                }else if(jQuery(this).hasClass('last-page')){//If last page button, go to last page
                    strNewPage=iPages;
                }

                jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).attr('page', strNewPage); //Set the new page attr value
                var iLastComment = (jQuery('.comment-pagination-control',jQuery('#'+mstrcontid)).attr('page'))*(iComPerPage); //Find the index of the last VISIBLE comment for this page
                var iFirstComment = iLastComment-iComPerPage; //Find the index of the first VISIBLE comment for this page
                    objComments.hide(); //Hide ALL current comments
                for(i=iFirstComment;i<iLastComment;i++){ //Show only the comments attached to the current page
                    objComments.filter(':eq('+i+')').css('display','block');
                }
                GeneratePageControl(); //Generate updated control bar
                document.getElementById('comments-top').scrollIntoView(true);//Scroll to top of comments section
            });
        });
    }
}

/********************************************************************************
 * addFlashVid()
 * 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){
	//console.log('Starting flash vid');
    var myDisplay = 'none';
    var btnDisplay = 'block';
    //Base URL for player assets (FLVPlayer_Progressive.swf, clearSkin_3.swf, play-button.png)
    var strBaseURL = '/media/video/';
    //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>\
    ';
	//console.log(returnHTML);
	document.write(returnHTML);
    //return returnHTML;
}