/********************************************************************************
 * 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')
  ********************************************************************************/
var pmGlobals = {
    /**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))
}

/********************************************************************************
 * !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($){
  /**
   * 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.
   */
  $.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.
   */
  $.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.
   */
  $.getCookie = function( name ){
    var value = document.cookie.match('(?:^|;)\\s*' + name.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1') + '=([^;]*)');
    return (value) ? decodeURIComponent(value[1]) : null;
  };

})(jQuery);

/********************************************************************************
 * 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){

    //Base URL for player assets (FLVPlayer_Progressive.swf, clearSkin_3.swf, play-button.png)
    var strBaseURL = '/media/';
    console.log(strVidURL);
    //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==''){var myDisplay='block';}else{var myDisplay='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:none;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").fadeTo(300,1);\n\
                },function(){\n\
                    jQuery("#'+strPlayerID+'-poster img").fadeTo(300,0.5);\n\
            }).click(function(){\n\
                jQuery("#'+strPlayerID+'-poster").fadeOut(function(){\n\
                    jQuery("#'+strPlayerID+'-video").show();\n\
                });\n\
            });\n\
        </scr'+'ipt>\
    ';
    return returnHTML;
}

/**
 * Adds a Vimdeo video to a container on the page
 */
function addVimeo(videoid,targetsel){
    $(targetsel).html('<iframe src="http://player.vimeo.com/video/'+videoid+'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="560" height="314" frameborder="0"></iframe>').fadeIn('normal');
}

/**
 * Returns true if matched string is a valid email address.
 */
jQuery.fn.isEmail = function(){
    return ($(this).val().match(/^([a-zA-Z0-9_\-\.]*)([a-zA-Z0-9]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/)) ? false : true;
}

/**
 * Returns true if matched string is a valid US postal code (long or short)
 */
jQuery.fn.isPostCode = function(){
    return ($(this).val().match(/^\d{5}([\s\-]\d{4})?$/)) ? false : true;
}

/**
 * Returns true if matched string is a valid US postal code (long or short)
 */
jQuery.fn.isRequired = function(){
    return ($(this).val().replace(/^\s+|\s+$/g, '')=='') ? true : false;
}

/******************************************************************************/
/**************************** DOM ONLOADED ************************************/
/******************************************************************************/
$(function(){
    var anchor = unescape(document.location.hash.substring(1));
    

    $('#newsSubmit').click(function(){
        if(!$('#cons_first_name').isRequired()
            && !$('#cons_last_name').isRequired()
            && !$('#cons_zip_code').isPostCode()
            && !$('#cons_email').isEmail()){
                //Post to API
                $.post(
                    '/api/',
                    {
                        'do':'newssignup',
                        '1337_4960_5_6624':'COM-Website-Undercover website',
                        cons_info_component:'t',
                        cons_mail_opt_in:'t',
                        cons_email_opt_in:'on',
                        cons_email_opt_in_requested:'true',
                        cons_first_name:$('#cons_first_name').val(),
                        cons_last_name:$('#cons_last_name').val(),
                        cons_zip_code:$('#cons_zip_code').val(),
                        cons_email:$('#cons_email').val(),
                        ACTION_SUBMIT_SURVEY_RESPONSE:'Sign Up!',
                        SURVEY_ID:'4960'
                    },
                    function(){
                        alert('Thank you for signing up!');
                        $('#lightbox').fadeOut(1000);
                        //console.log('POST request sent.');
                    });
            }else{
                $('#cons_first_name, #cons_last_name, #cons_zip_code, #cons_email').blur();
            }
            return false;
    });
})
