

$(function() {

     uploadFileButton_init();                 // upload button

     formValidation_init();                  // form validation
     
     signInForm_init();                      // sign-in form - top right
     externalLinks_init();                   // external links

     clues_init();                       //clue page
    
     if ($("#twitter-feed").length) {
          homepageTwitterfeed_init();   // Home page twitter feed
     }

     roversRewardsForm_init();           // Rover's Rewards - upload
     
     if( $('body#page-rewards-gallery').length>0 ){
          roversRewardsGallery.init();        // rover's rewards - gallery
     }
    
     if( $('.mediagallery').length>0 ){
          homePageGallery_init();       // home page gallery
     }
    
     phase1_homePage();                 // Home page gallery (phase 1 only)
    
});


// =====================================================================================================
// GLOBAL / GENERAL
// =====================================================================================================

function externalLinks_init()
{
     $("a[rel=external]").each(function() {
        $(this).addClass('external');
        $(this).attr({
            title: "Open this page in a new window",
            target: "_blank"
        });
    });
}

function signInForm_init()
{
     $('.compactForm input').focus(function() {
        $('label[for=' + $(this).attr('id') + ']').hide();
    });
    $('.compactForm input').each(function(ele) {
        if ($(this).val().length > 0)
            $('label[for=' + $(this).attr('id') + ']').css({ display: "none" });
    });
    $('.compactForm input').blur(function() {
        if ($(this).val().length == 0)
            $('label[for=' + $(this).attr('id') + ']').show();
    });
    $('.compactForm').removeClass('compactForm');
}

function uploadFileButton_init()
{
     $("input[type=file]").filestyle({
        image: "assets/images/buttons/choose-file.gif",
        imageheight: 24,
        imagewidth: 95,
        width: 110
    });

    // adjust tabIndex and accesskeys after filestyle treatment

    $("input.file").each(function() {
        $(this).attr("accesskey", $(this).next("div").children("input").attr("accesskey"));
        $(this).attr("tabindex", $(this).next("div").children("input").attr("tabindex"));

        $(this).next("div").children("input").removeAttr("accesskey");
        $(this).next("div").children("input").removeAttr("tabindex");
    });
}

// =====================================================================================================
// HOME PAGE TWITTER FEED
// =====================================================================================================

function homepageTwitterfeed_init()
{
     $.Juitter.start({
         searchType: "fromUser", // needed, you can use "searchWord", "fromUser", "toUser"
         //searchObject:"abcnews", // only for testing!
         searchObject: "Dorothy_LostDog",
         lang: "en",
         live: "live-20",
         placeHolder: "twitter-feed",
         loadMSG: "Loading messages...",
         total: 10,
         onTransitionStart: onJuitterTransitionStart,
         onTransitionComplete: onJuitterTransitionComplete
     });

    $('#next-tweet a').click(function() {
        twitterScroll('+');
        return false;
    });

    $('#prev-tweet a').click(function() {
        twitterScroll('-');
        return false;
    });
}

// TWITTER FEED CONTROL METHODS

var allowScroll = true;

function twitterScroll( direction )
{
     if( allowScroll ){
          allowScroll = false;
          $('#twitter-feed').animate({
               top: twitterScrollDistance( direction )
          }, 300, function() {
               scrollBtnCheck();
               allowScroll = true;
          });
     }
}

function onJuitterTransitionStart()
{
     allowScroll = false;
}

function onJuitterTransitionComplete()
{
     allowScroll = true;
     scrollBtnCheck();
}

function scrollBtnCheck()
{
     var listHeight = $('#twitter-feed').height();
     var itemHeight = $('#twitter-feed .twittLI:first').height();
     var yPosStr = $('#twitter-feed').css( "top" );
     var yPos = yPosStr.slice( 0, yPosStr.indexOf('p') );
     
     if( yPos >= 0 ){
          $('#next-tweet').addClass( 'disabled' );
     }else{
          $('#next-tweet').removeClass( 'disabled' );
     }
     
     if( yPos <= ( 0 - ( listHeight - itemHeight ) ) ){
          $('#prev-tweet').addClass( 'disabled' );
     }else{
          $('#prev-tweet').removeClass( 'disabled' );
     }
}

function twitterScrollDistance( direction )
{
     var itemHeight = $('#twitter-feed .twittLI:first').height();
     scrollBtnCheck();
     itemHeight = ( (direction == '+') && $('#next-tweet').hasClass( 'disabled' ) )?0:itemHeight;
     itemHeight = ( (direction == '-') && $('#prev-tweet').hasClass( 'disabled' ) )?0:itemHeight;
     return direction + "=" + itemHeight;
}

// =====================================================================================================
// YOUTUBE CREATION
// =====================================================================================================

function createYouTubeHTML( youTubeID, playerWidth, playerHeight )
{
     var youTubeHTML;
     
     var ytH = ( playerHeight != undefined )?playerHeight:Math.round(playerWidth*.75) + 24;
     var ytCol1 = '0x4e2d1d';
     var ytCol2 = '0xddbe92';
     
     var agent=navigator.userAgent.toLowerCase();
     var is_iPhone = (agent.indexOf('iphone')!=-1);
     
     if( is_iPhone ){
          youTubeHTML = '<embed id="ytObject" src="http://www.youtube.com/v/' + youTubeID + '?enablejsapi=1&hl=en_US&fs=1&rel=0&color1=' + ytCol1 + '&color2=' + ytCol2 + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + playerWidth + '" height="' + ytH + '"></embed>';
     }else{
          if( $.flash.available ){
               youTubeHTML = $.flash.create(
               {
                    swf: 'http://www.youtube.com/v/' + youTubeID + '?enablejsapi=1&hl=en_US&fs=1&rel=0',
                    width: playerWidth,
                    height: ytH,
                    id: 'ytObject',
                    flashvars: {   color1: ytCol1,
                                   color2: ytCol2
                                   },
                    params: {      allowFullScreen: 'true',
                                   allowscriptaccess: 'always',
                                   name3: 'Plugin'   }
               } );
          }
     }
     
     return youTubeHTML;
     
}


// =====================================================================================================
// HOME PAGE GALLERY (PHASE 1 only)
// =====================================================================================================

function phase1_homePage()
{     
     var ytHtml = createYouTubeHTML( 'demOzTtxuVQ', 402 );
     if( ytHtml ){
          $('#youtube').html( ytHtml );
     }
}

// =====================================================================================================
// HOME PAGE GALLERY
// =====================================================================================================

function homePageGallery_init()
{
          // HOME PAGE MEDIA NAV
           
           var totalThumbItems = $('#mediagallery-thumbs li').length;
           var thumbItemWidth  = $('#mediagallery-thumbs li:first').width();
           
           $('.mediagallery-nav').addClass('scrollGallery');
           
           $('#mediagallery-thumbs li').each( function( i ){
                 $(this).css({'float':'none','position':'absolute','left':i*thumbItemWidth+'px'});
            });
           
           var totalThumbItems = $('#mediagallery-thumbs li').length;
           var thumbItemWidth  = $('#mediagallery-thumbs li:first').width();
           
           $('#mediagallery-thumbs ul').width( totalThumbItems*thumbItemWidth );
          
          $('#prev-media a').click(function() {
              mediaThumbScroll('+');
              return false;
          });
      
          $('#next-media a').click(function() {
              mediaThumbScroll('-');
              return false;
          });
          
          //
          
          $('#mediagallery-thumbs a').click(function(e) {
                e.preventDefault();
                e.stopPropagation();
                $('#mediagallery-thumbs li').each(function(){
                     if( $(this).hasClass('selected') ){ $(this).removeClass('selected') };
                });
                $(this).parent('li').addClass('selected');
                populateMediaContent( $(this).attr('title'), $(this).attr('href') );
                return false;
          });
          
          $('#mediagallery-thumbs a').hover(
               function(e) {
                         
                         var thumbX = Number( $(this).parent().css('left').slice( 0, $(this).parent().css('left').indexOf('px')) );
                         var thumbW = $(this).parent().width();
                         var toolTipW;
                         var thumblistX = Number( $('#mediagallery-thumbs ul').css('left').slice( 0, $('#mediagallery-thumbs ul').css('left').indexOf('px')) );
                         var offsetX = Number( $('#mediagallery-thumbs').css('left').slice( 0, $('#mediagallery-thumbs').css('left').indexOf('px')) );
                         var shiftX = Math.round((thumbW/100)*70);
                         var newThumbX = thumblistX + thumbX + offsetX;
                         
                         $('#mediagallery-tooltip').html( thumbTitle = $(this).attr('title') );
                         toolTipW = $('#mediagallery-tooltip').width() + Number( $('#mediagallery-tooltip').css('paddingLeft').slice( 0, $('#mediagallery-tooltip').css('paddingLeft').indexOf('px')) )*2;
                                                                      
                         if( newThumbX < ($('#mediagallery-thumbs').width()/2) )
                         {
                              $('#mediagallery-tooltip').css( { 'left':newThumbX + shiftX + 'px',
                                                                 'textAlign':'left',
                                                                 'backgroundPosition':'bottom left'} );
                         }else{
                              $('#mediagallery-tooltip').css( { 'left': ((newThumbX + thumbW)-toolTipW-shiftX) + 'px',
                                                                 'textAlign':'right',
                                                                 'backgroundPosition':'bottom right'} );
                         }
                         
                         $('#mediagallery-tooltip').show();
                         
                         
                    },
                    function(e) {
                         $('#mediagallery-tooltip').hide();
                         $('#mediagallery-tooltip').html('');
               }
          );
          
          mediaThumbScrollBtnCheck();
          $('#mediagallery-thumbs a:first').click();
}


function populateMediaContent( contentTitle, contentSrc )
{
     // set title
     $('#media-title').html( contentTitle );
     if( $( '#ytObject' ).length < 1 ){
          $('#media .content').html('');
     }

     // check type
     if( contentSrc.indexOf('youtube') > -1 ){
          loadYouTubeVid( contentSrc );
     }else{
          loadImage( contentSrc )
     }
}

function loadYouTubeVid( src )
{

     var ytVidId = src.slice( src.indexOf('=')+1, src.length );
     var ytW = 382;
     var ytH = Math.round(ytW*.75) + 24;
     
     var ytHtml = createYouTubeHTML( ytVidId, ytW );
     
     if( $('#media').height() != ytH ){
          $('#media').animate({
               height: ytH
          }, 300, function() {
               if( ytHtml ){
                    $('#media .content').html( ytHtml );
               }
          });
     }else{
          if( $( '#ytObject' ).length < 1 ){
               if( ytHtml ){
                    $('#media .content').html( ytHtml );
               }
          }else{
               var ytswf = $( '#ytObject' )[0];
               ytswf.loadVideoById( ytVidId, 0 );
          }
     }
}

function loadImage( src )
{
     var currentFullSrc;
     var currentSrc;
     
     if( $('.productPhoto').length != 0 ){
          currentFullSrc = $('.productPhoto').attr('src');
          currentSrc = currentFullSrc.slice( 0, currentFullSrc.indexOf('?') );
     }

     if ( (currentSrc != src) || ( $('.productPhoto').length == 0 ) ) {
             
             // adding a query gets around IE's issue with not triggering load() on cached images
             var q = '?nocache=' + (new Date()).getTime();
             $('<img />').attr('src', src + q )
                                     .addClass('productPhoto')
                                     .load( function(){

                                        $('#media .content').html($(this).hide()).parent('#media').animate({
                                             height: $('#media .content img').height()
                                        }, 300, function(){ $('#media .content img').fadeIn() } );
                                             
                                   });
     }

}

// --------------------------------------------------
// Thumbnail gallery scrolling
// --------------------------------------------------

var allowThumbScroll = true;

function mediaThumbScroll( direction )
{
     if( allowThumbScroll ){
          allowThumbScroll = false;
          $('#mediagallery-thumbs ul').animate({
               left: mediaThumbScrollDistance( direction )
          }, 300, function() {
               mediaThumbScrollBtnCheck();
               allowThumbScroll = true;
          });
     }
}

function mediaThumbScrollBtnCheck()
{

     var listWidth = $('#mediagallery-thumbs').width();
     var itemWidth = $( '#mediagallery-thumbs ul' ).width();
     var xPosStr = $('#mediagallery-thumbs ul').css( "left" );
     var xPos = xPosStr.slice( 0, xPosStr.indexOf('p') );
     
     if( xPos >= 0 ){
          $('#prev-media').addClass( 'disabled' );
     }else{
          $('#prev-media').removeClass( 'disabled' );
     }
     
     if( xPos <= ( 0 - ( itemWidth - listWidth ) ) ){
          $('#next-media').addClass( 'disabled' );
     }else{
          $('#next-media').removeClass( 'disabled' );
     }
}

function mediaThumbScrollDistance( direction )
{
     var itemWidth = $( '#mediagallery-thumbs li:first' ).width();
     mediaThumbScrollBtnCheck();
     itemWidth = ( (direction == '-') && $('#next-media').hasClass( 'disabled' ) )?0:itemWidth;
     itemWidth = ( (direction == '+') && $('#prev-media').hasClass( 'disabled' ) )?0:itemWidth;
     return direction + "=" + itemWidth;
}

// =====================================================================================================
// REGISTER NOW VALIDATION
// =====================================================================================================

function formValidation_init()
{
     
     $('#ctl00_ctl00_cphBase_cphMain_ddlDayBirth, #ctl00_ctl00_cphBase_cphMain_ddlMonthBirth, #ctl00_ctl00_cphBase_cphMain_ddlYearBirth').change(function() {
        DOBValidator(null, null);
    });

    checkDogOwner();
    $("input[name='ctl00$ctl00$cphBase$cphMain$rdoDogOwner']").change(function() {
        checkDogOwner();
        DogOwnerValidator(null, null);
    });

    $('#ctl00_ctl00_cphBase_cphMain_txtDogName').blur(function() {
        DogNameValidator(null, null);
    });

    $('#ctl00_ctl00_cphBase_cphMain_cboReceiptCopy').change(function() {
        ReceiptValidator(null, null);
    });

    $('#ctl00_ctl00_cphBase_cphMain_cboTermsConditions').change(function() {
        TermsCondValidator(null, null);
    });
    
    $('#ctl00_ctl00_cphBase_cphMain_cboEntryConditions').change(function() {
        EntryCondValidator(null, null);
    });

    $('.required').blur(function() { toggleLiErrorClass(); });
    $('select.required').change(function() { toggleLiErrorClass(); });
    $('span.required input[type="radio"]').change(function() { toggleLiErrorClass(); });
    $('span.required input[type="checkbox"]').change(function() { toggleLiErrorClass(); });
    $('.action-button').click(function() { toggleLiErrorClass(); });
    $('.required').keypress(function(e) {
        if (e.keyCode == '13')
            toggleLiErrorClass();
    });
    $('#UploadVideo').change(function() { validateFileInput(); toggleLiErrorClass(); });
 
 
    // Maxlength restrictions on textareas
    $('.maxlength500').keyup(function() {
        if ($(this).val().length > 500)
            $(this).val($(this).val().substring(0,500));
    });

    $('.maxlength50').keyup(function() {
        if ($(this).val().length > 50)
            $(this).val($(this).val().substring(0, 50));
    });
    
    // Sets to 1 to show javascript is enabled
    $('#JavascriptEnabled').val('1');
}

// --------------------------------------------------
// Form validation functions
// --------------------------------------------------

function checkDogOwner(){
     if( $("input[name='ctl00$ctl00$cphBase$cphMain$rdoDogOwner']:checked").val() == 'rdoDogOwnerYes' )
          $("#ctl00_ctl00_cphBase_cphMain_liDogName").show();
     else
          $("#ctl00_ctl00_cphBase_cphMain_liDogName").hide();
}

function DogOwnerValidator(source, arguments) {
    if ($("#ctl00_ctl00_cphBase_cphMain_rdoDogOwnerYes").attr('checked') ||
        $("#ctl00_ctl00_cphBase_cphMain_rdoDogOwnerNo").attr('checked')) {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDogOwner').hide();
        else
            arguments.IsValid = true;
    } else {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDogOwner').show();
        else
            arguments.IsValid = false;
    }
} 

function DogNameValidator(source, arguments) {
    if( $("input[name='ctl00$ctl00$cphBase$cphMain$rdoDogOwner']:checked").val() == 'rdoDogOwnerYes' &&
        $("input[name='ctl00$ctl00$cphBase$cphMain$txtDogName']").val() == '' )
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDogName').show();
        else
            arguments.IsValid = false;
    else 
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDogName').hide();
        else
            arguments.IsValid = true;
}

function ReceiptValidator(source, arguments) {
    if ($('#ctl00_ctl00_cphBase_cphMain_cboReceiptCopy').attr('checked')) {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvReceiptCopy').hide();
        else
            arguments.IsValid = true;
    } else {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvReceiptCopy').show();
        else
            arguments.IsValid = false;
    }
}

function TermsCondValidator(source, arguments) {
    if ($('#ctl00_ctl00_cphBase_cphMain_cboTermsConditions').attr('checked')) {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvTermsConditions').hide();
        else
            arguments.IsValid = true;
    } else {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvTermsConditions').show();
        else
            arguments.IsValid = false;
    }
}

function EntryCondValidator(source, arguments) {
    if ($('#ctl00_ctl00_cphBase_cphMain_cboEntryConditions').attr('checked')) {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvEntryConditions').hide();
        else
            arguments.IsValid = true;
    } else {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvEntryConditions').show();
        else
            arguments.IsValid = false;
    }
}

function DOBValidator(source, arguments) {
    if ( $('#ctl00_ctl00_cphBase_cphMain_ddlDayBirth').val() != 'DD' &&
         $('#ctl00_ctl00_cphBase_cphMain_ddlMonthBirth').val() != 'MM' &&
         $('#ctl00_ctl00_cphBase_cphMain_ddlYearBirth').val() != 'YYYY' ) {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDOB').hide();
        else
            arguments.IsValid = true;    
    } else {
        if (arguments == null)
            $('#ctl00_ctl00_cphBase_cphMain_cvDOB').show();
        else
            arguments.IsValid = false;
    }
}

function toggleLiErrorClass() {
    $('.required').each(function() {
        var parentLi = $(this).closest('li');
        if (parentLi.find('span.error').css('display') == 'none')
            parentLi.removeClass('error');
        else
            parentLi.addClass('error');
    });
}

// =====================================================================================================
// CLUES PAGE
// =====================================================================================================

function clues_init()
{
     
     $("#clue").hide();

    var clueListHeight;

    $("#clue-list li a").each(function() {
        var href = $(this).attr("href");
        $(this).click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            clueListHeight = $("#all-clues").height();
            $("#all-clues").height(clueListHeight);
            $("#ajax-loader").show();
            $("#clue-list").fadeOut("fast", function() {
                // load data, then fade back in
                $("#clue").fadeIn()
            });
            $.ajax({ url: href,
                type: "POST",
                data: { ajaxapp: "1" },
                success: function(response) {
                    $("#ajax-clue").hide().html(response);
                    if ($("#ajax-clue img").length) {
                        $("#ajax-clue img").load(function() {
                            $("#ajax-loader").hide();
                            $("#ajax-clue").show();
                        });
                    } else {
                        $("#ajax-loader").hide();
                        $("#ajax-clue").show();
                    }
                }
            });


        });
    });

    $("#clue .close-btn").click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#clue").fadeOut("fast", function() {
            $("#clue-list").fadeIn("fast", function() {
                $("#all-clues").css('height', 'auto');
                $("#ajax-clue").html("");
            })
        });
    });
     
}

// =====================================================================================================
// ROVER'S REWARDS - ENTRY UPLOAD
// =====================================================================================================

function roversRewardsForm_init()
{
     
     $('.btnUpload').click(function(e) {
        e.preventDefault();
        e.stopPropagation();

        if (validateFileInput() && Page_IsValid) {
            var form = $('#aspnetForm');
            
            $('#upload-loader').show();
            
            form.attr('action', $('#UploadURL').val());
            form.attr('enctype', 'multipart/form-data');
            form.attr('encoding', 'multipart/form-data');              
            form.attr('target', 'UploadIFrame');
            form.submit();
            form.attr('action', window.location.pathname);
            form.removeAttr('enctype');
            //form.removeAttr('encoding');
            form.removeAttr('target');
        }

        return false;
    });     
     
}

// =====================================================================================================
// ROVER'S REWARDS - GALLERY
// =====================================================================================================

var roversRewardsGallery = {
     
     selectedIndex : undefined,
     selectedYtId: '',
     selectedId: '',
     init: function()
     {
          $('#rover-detail').hide();
          
          $( '#rover-thumbs li' ).each( roversRewardsGallery.initThumbnail );
          
          starRating_init();
          
          $( '#video-container .close' ).live('click', function(e){
               e.preventDefault();
               e.stopPropagation();
               roversRewardsGallery.selectItem();
               return false;
          });
          
          this.initEmailField();
          this.initToolTip();
          this.initSubmit();
     },
     insertYouTube: function()
     {
          if( $( '#ytObject' ).length < 1 ){
               $( '#video' ).html( '' );
               $( '#video' ).html( createYouTubeHTML( roversRewardsGallery.selectedYtId, 409, 333 ) );
          }else{
               var ytswf = $( '#ytObject' )[0];
               ytswf.loadVideoById( roversRewardsGallery.selectedYtId, 0 );
          }
     },
     initThumbnail: function( index ){
          $( this ).click( function( e ){
               e.preventDefault();
               e.stopPropagation();

               var src = $(this).children('a').attr('href');
               var sliceA = src.slice( src.indexOf('video=')+6, src.length );
               var sliceB = ( sliceA.indexOf('&') < 0 )?sliceA.length:sliceA.indexOf('&');

               roversRewardsGallery.selectedId = sliceA.slice( 0, sliceB );
               roversRewardsGallery.selectItem( index );
               
               $.scrollTo('#content-column', 'fast');
               return false;
          });
     },
     selectItem: function( itemIndex ){
          if( itemIndex != undefined ){
               if( itemIndex != this.selectedIndex ){
                    $( '#rover-thumbs li' ).removeClass('selected').eq(itemIndex).addClass('selected'); 
                    this.showGalleryItem(itemIndex);
               }
          }else{
               this.hideGalleryItem();
          }
          roversRewardsGallery.selectedIndex = itemIndex;
     },
     showGalleryItem: function(itemIndex){
          
          // update Rover's full description content
          $.ajax({  url: 'rovers-rewards-details.aspx',
                    type: 'POST',
                    data: { ajaxapp: '1', 
                            selectedID: roversRewardsGallery.selectedId },
                    success: function(response) {
                        $('#rover-ajax').hide().html(response);
                        starRating_init();
                        roversRewardsGallery.initEmailField();
                        roversRewardsGallery.initToolTip();
                        roversRewardsGallery.initSubmit();
                        $('#rover-ajax').fadeIn('fast');
                    },
                    error: function() {
                        alert('An unkown error occured, please try again later.');
                    }
           });
          
          $('#rover-intro').hide();
          $('#rover-detail').show();
     },
     hideGalleryItem: function(){
          $('#rover-ajax').html( '' );
          $('#rover-detail').hide();
          $('#rover-intro').fadeIn('fast');
          $('#rover-thumbs li').removeClass('selected');
     },
     initEmailField: function( emailString ){
          
          var msg = $( '#email-address' ).val();
          
          this.disableSubmit( $( '#email-address' ).val() );
          
          $( '#email-address' ).focus( function(){
               if ($.trim($(this).val()) == msg ){
                    $(this).val('');     
               };
               roversRewardsGallery.disableSubmit( $(this).val() );
          });
          $( '#email-address' ).blur( function(){
               if ( $(this).val().length < 1){
                    $(this).val(msg);
               };
              roversRewardsGallery.disableSubmit( $(this).val() );
          });
          $( '#email-address' ).change(function(event) {
               roversRewardsGallery.disableSubmit( $(this).val() );
          });
          $( '#email-address' ).keypress(function(event) {
               roversRewardsGallery.disableSubmit( $(this).val() );
          });
          $( '#email-address' ).keyup(function(event) {
               roversRewardsGallery.disableSubmit( $(this).val() );
          });
          $( '#email-address' ).click(function(event) {
               roversRewardsGallery.disableSubmit( $(this).val() );
          });
     },
     disableSubmit: function( value ){
          if( this.testEmail( value ) ){
               $( '#rating-submit' ).removeAttr( 'disabled' );
               $( '#rating-submit' ).removeClass( 'disabled' );     
          }else{
               $( '#rating-submit' ).attr( 'disabled', 'disabled' );
               $( '#rating-submit' ).addClass( 'disabled' );
          }
     },
     testEmail: function(value){
          // http://docs.jquery.com/Plugins/Validation/Methods/email
          // from: jquery.validate.js
          // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
          return ( /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value) );
     },
     initToolTip: function(){
         $('#rating-help').css({ 'clear':'none', 'position':'absolute', 'bottom':33, 'right':40 });
         $('#rating-help').hide();
         $('#rating-submit-question').hover( function(){$('#rating-help').show()},
                                             function(){$('#rating-help').hide()} );
     },
     initSubmit: function(){
          $('#rating-submit').click( function()
          {
               // SEND DATA HERE?
               $.ajax({ url: 'rovers-rewards-vote.aspx',
                        type: 'POST',
                        dataType: 'json',
                        data: { ajaxapp: '1', 
                                SelectedID: $('#hdnBestHelperID').val(),
                                Email: $('#email-address').val(),
                                Vote: $('#average-rating').val() },
                        success: function(json) {
                            if (json.success.toLowerCase() == 'true')
                                roversRewardsGallery.submitSuccess();
                            else {
                                roversRewardsGallery.submitFail(json.msg);
                            }
                        },
                        error: function() {
                            roversRewardsGallery.submitFail('An error has occurred.<br />Please <a href=\"#\">try again</a>.');
                        }
               });
          });
     },
     submitSuccess: function(){
          $('#email-address').fadeOut('fast');
          $('#rating-help').remove();
          $('#rating-submit-question').fadeOut('fast');
          $('#rating-submit').fadeOut('fast');
          $('#rating-form label').hide('fast', function(){
               $('#rating-message').hide().width(270).html("<strong>Thanks!</strong> An email has been sent to you. Click the link in the email to make your rating count.").fadeIn('fast');
     
          });
          starRating_disable();
     },
     submitFail: function(errorMsg){
          $('#rating-submit').fadeOut('fast');
          $('#rating-submit-question').fadeOut('fast');
          $('#email-address').fadeOut('fast', function(){
               $('#rating-message').hide().width(200)
                    .html(errorMsg)
                    .fadeIn('fast')
                    .click( function(e){
                         e.preventDefault();
                         e.stopPropagation();
                         $('#rating-message').fadeOut('fast', function(){
                              $(this).html('');
                              $(this).unbind();
                              $('#rating-submit').fadeIn('fast');
                              $('#rating-submit-question').fadeIn('fast');
                              $('#email-address').fadeIn('fast')
                         });
                         return false;
                    });
          });
     }
     
};

function starRating_init()
{
     var avRating = Number( $('#average-rating').val() );
     
     var styledStarsHTML = '<div class="rating-stars">';
     $('input.star').each(function(i){
          styledStarsHTML += (i<avRating)?'<span class="star">*</span>':'<span>-</span>';
     });			
     styledStarsHTML += '</div>';
     
     $('#rating-form label').after(styledStarsHTML); 
     
     $('input.star').remove();
     
     $('#rating-form').append('<input type="hidden" name="stars" value="' + $('#average-rating').val() + '" id="stars" />');
     $('.rating-stars span').hover(function() {
          var starIndex = $('.rating-stars span').index(this);
          $('.rating-stars span').each(function(index) {
               if (index <= starIndex) $(this).addClass('star');
               else $(this).removeClass('star');
          });
     }).click(function() {
          var rating = $('.rating-stars span').index(this) + 1;
          $('#average-rating').val(rating);
          $('#stars').val(rating);
     });
     $('.rating-stars').mouseleave(function() {
          $('.rating-stars span').each(function(index) {
               if (index < $('#average-rating').val() )
               {
                    $(this).addClass('star');
               }
               else $(this).removeClass('star');
          });
     });  
}

function starRating_disable()
{
     $('.rating-stars').unbind();
     $('.rating-stars span').unbind();
}


// =====================================================================================================
// YOUTUBE UPLOADER VALIDATION
// =====================================================================================================

var hash = {
    '3g2': 1,
    '3gp': 1,
    'asf': 1,
    'asx': 1,
    'avi': 1,
    'flv': 1,
    'mov': 1,
    'mpg': 1,
    'mpeg': 1,
    'mp4': 1,
    'rm': 1,
    'swf': 1,
    'vob': 1,
    'wmv': 1
};

//----------------------------------
// Validates file extension in file 
// element 
function check_extension(filename) {
    if (filename === "")
        return false;

    var re = /\.([^.]+)$/;
    var ext = filename.toLowerCase().match(re);

    return hash[ext[1]] == 1 ? true : false;
}

//----------------------------------
// Validates file input
function validateFileInput()
{
    var valid = false;
    if ($('#UploadVideo').val().length == 0) {
        $('#videoErrorMsg').html('Please select your video').show();
    } else if (check_extension($('#UploadVideo').val()) == false) {
        $('#videoErrorMsg').html('Sorry, that video format is not supported').show();
    } else {
        $('#videoErrorMsg').hide();
        valid = true;
    }

    toggleLiErrorClass();
    return valid;
}
