function clog(str) {
	if ((typeof console)!="undefined")
		console.info(str);
}

function debugmsg(subject,msg) {
	if ((typeof msg)=="undefined") {
		msg = browserInfo();
	} else {
		msg += "\n"+browserInfo();
	}
	$.post('/debug/',{'data':subject+"\n"+msg});
}

function browserInfo() {
	out = ["Browser Info","----------------"];
	for (field in navigator) {
		out.push(field+": "+navigator[field]);
	}
	out.push("User Info");
	out.push("----------------");
	if ((typeof uname) != "undefined") {
	    out.push("Username: "+uname);
	}
	if ((typeof selectedfiles) != "undefined") {
	    out.push("Files selected:");
	    for (file in selectfiles) {
		out.push("    "+selectedfiles[file]);
	    }
	}
	return out.join("\n");
}

(function($) {
  $.smartPoller = function(wait, poller) {
    if ($.isFunction(wait)) {
      poller = wait;
      wait = 1000;
    }
 
    (function startPoller() {
      setTimeout(function() {
        poller.call(this, startPoller);
      }, wait);
      wait = (wait<(30*60*1000))?(wait * 1.02):(30*60*1000); // cap at 30 secs
    })();
  }
})(jQuery);


var globaldate = new Date();

// shows alert message when motion is detected.
  // when alerts are on, there should be an 'on' class on #motion_detected
  // this will make the alert message say 'motion detected, email sent'
  // rather than just 'motion detected'
  function fire_alert(test){
    if (test=="test")
        motion_detected_text = $('#motion_detected_text_test');
    else if (test=="outside_limit")
	motion_detected_text = $('#motion_detected_text_outside_limit');
    else
        motion_detected_text = $('#motion_detected_text');
    motion_detected_text.fadeIn('fast');
    
    setTimeout(function(){
      motion_detected_text.fadeOut('fast');
    }, 3000);
  }


description_text = {
    "unwelcome_visitor":"A visitor enters the office after hours. Can you find him in the original video?",
    "rabbit_cage":"Kaylee and Cadbury, the rabbits that inspired us to create HighlightCam."
};
example_highlight = {
    "unwelcome_visitor":{"file":"http://videos.highlightcam.com.s3.amazonaws.com/video_70e52caefabd4dd8be0477d0f7dc6151.flv","image":"http://preview_image.highlightcam.com.s3.amazonaws.com/preview_image_70e52caefabd4dd8be0477d0f7dc6151.jpg"},
    "rabbit_cage":{"file":"http://videos.highlightcam.com.s3.amazonaws.com/video_e592d57103ca46af8eb6c07f96b202e1.flv","image":"http://preview_image.highlightcam.com.s3.amazonaws.com/preview_image_e592d57103ca46af8eb6c07f96b202e1.jpg"}
};
example_original = {"unwelcome_visitor":{"file":"http://videos.highlightcam.com.s3.amazonaws.com/video_a985d2d3209342f7bd04ef497ba2b2a8.flv","image":"http://preview_image.highlightcam.com.s3.amazonaws.com/preview_image_a985d2d3209342f7bd04ef497ba2b2a8.jpg"},
    "rabbit_cage":{"file":"http://videos.highlightcam.com.s3.amazonaws.com/video_e074e9c88302437080a9b6c57200601e.flv","image":"http://preview_image.highlightcam.com.s3.amazonaws.com/preview_image_e074e9c88302437080a9b6c57200601e.jpg"}
};

function initialize_carousel()
  {
    $('#clip_viewer.carousel #carousel_wrap li').unbind('click');
    // initialize carousel
    $('#clip_viewer.carousel #carousel_wrap').serialScroll( {
      items:'li',
      prev:'a.prev',
      next:'a.next',
      ofset:-40,
      start:0,
      duration:600,
      constant: false,
      force:false,
      stop:true,
      lock:false,
      cycle:false,
      //easing:'easeOutQuart',
      jump: true,
      onBefore:function(e,elem,$pane,$items,pos) {
        if ($(elem).hasClass('videoitem'))
            select(elem);
      //   key = "tb"+(parseInt(pos)+1);
      //   select(key);
      }
    });
  }  
  
  function destroy_carousel()
  {
    $('#clip_viewer.carousel #carousel_wrap li, .next, .prev').unbind('click');
    $('#clip_viewer.carousel #carousel_wrap').unbind('serialScroll');

    $('#clip_viewer.carousel #carousel_wrap li').bind('click',function () { select($(this)) });
  }

 function strip_view()
  {
    // sets width that accomodates all the slides
    var carousel_ul = $('#clip_viewer.carousel ul');
    var lis = $('li', carousel_ul);
    var first_li = $(lis[0]);
    var li_width = first_li.width() + parseInt(first_li.css('margin-right') + 4);
    var ul_width = (li_width * lis.size());
  
    // change this to 'auto' to enable scrollbars
    $('#clip_viewer.carousel #carousel_wrap').css({'overflow-x':'scroll', 'overflow-y':'hidden'});
    carousel_ul.css('width', ul_width);
    
    initialize_carousel();
  }
  
  function grid_view()
  {
    // resets width to standard, to accomodate grid view
    // unsets ul width
    $('#clip_viewer.carousel #carousel_wrap').css('overflow', 'hidden');
    $('#clip_viewer.carousel ul').css('width', '820px');
    $('#clip_viewer.carousel #carousel_wrap').scrollTo(0);
    
    destroy_carousel();
  }

$(function(){
  // homepage tabs
  $('#more_examples ul li a').click(function(){      
        var li = $(this).parent();
        var ul = li.parent();
        
        $('li.active', ul).removeClass('active');
        li.addClass('active');
    
        //console.log('load: ', $(this).attr('class'));
        document.getElementById('origply').sendEvent("LOAD",example_original[$(this).attr('class')]);
        document.getElementById('highply').sendEvent("LOAD",example_highlight[$(this).attr('class')]);

        document.getElementById('origply').sendEvent("PLAY","true");
        document.getElementById('highply').sendEvent("PLAY","true");

        $('#comparison_description p').text(description_text[$(this).attr('class')]);
        
        return false;    
  });
    
  // toggle mute and record buttons
  $('.start_recording, .stop_recording').click(function() {
    if($(this).hasClass('start_recording'))
    {
      $(this).removeClass('start_recording').addClass('stop_recording');
      $('span', $(this)).html('Stop Recording');
      unPauseButton();
      return false;
    }
    else
    {
      $(this).removeClass('stop_recording').addClass('start_recording'); 
      $('span', $(this)).html('Start Recording');
      pauseButton();
      return false;
    }
  });
  
  $('.start_muting, .stop_muting').click(function() {
    if($(this).hasClass('start_muting'))
    {
      $(this).removeClass('start_muting').addClass('stop_muting');
      $('span', $(this)).html('Unmute');
      document.getElementById('client').mute();
      return false;
    }
    else
    {
      $(this).removeClass('stop_muting').addClass('start_muting'); 
      $('span', $(this)).html('Mute');
      document.getElementById('client').unmute();
      return false;
    }
  })
  
  // allows for toggleable control boxes
  $('.can_toggle .toggle', $(this)).hide();

  $('.controls.can_toggle h2').click(function(){
    p = $(this).parent();
    if(! p.hasClass('open'))
    {
      $('.toggle', p).slideDown('fast');
      p.addClass('open');
      
    }
    else
    {
      $('.toggle', p).slideUp('fast', function(){
        p.removeClass('open');
      });
    }

  });
  
  // should start in 'strip mode'
  // running this here so it happens by default
  // if this is saved as a user preference, you will want
  // to decide to call or not on the backend
  strip_view();
  
  // bind grid / list view buttons
  $('.grid_view').click(function(){ grid_view(); return false; });
  $('.strip_view').click(function(){ strip_view(); return false; });
 
  // highlight text for easier copy/paste
  $('.share_link').click(function(){
    $(this).select();
  });
  
  
});

function register_via_ajax() {
    if (window.location.href.indexOf('webcam')!=-1) {
        $('#client').addClass('hiddenplayer');
    }
    if ($('#dbox').length>0) {
        $('#dbox').dialog('open');
    } else {
        $('<div id="dbox"><img src="/site_media/spinning_throbber.gif"/> Loading registration form...</div>').load('/ajax_register/').dialog({
            modal: true,
            height: 420,
            width: 460,
            resizable:false,
            draggable: false,
            title: 'Register &mdash; Claim your anonymous account',
            buttons: {
              'Submit Form':function () {
                $(this).load('/ajax_register/?'+(new Date().getTime()),{
                    'password1':$('#id_password1').val(),
                    'password2':$('#id_password2').val(),
                    'username':$('#id_username').val(),
                    'email':$('#id_email').val()
                    });
              }
            },
            close: function () {
                if (window.location.href.indexOf('webcam')!=-1) {
                   $('#client').removeClass('hiddenplayer');
                }
            }
        });
    }
}


function catchenter(e) {

    if(window.event) // IE
    {
        keynum = e.keyCode;
    } else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }

    if (keynum == 13) {
        submit_comment();
    } 
}

function submit_comment() {
    comment = $('#comment input#text').val();
    if (comment.length < 1) {
        return;
    }

    $('#comment').html('<img src="/site_media/spinning_throbber.gif"/> Sending...');

    $('#comment').load('/feedback_email/',{'text':comment});

}

function validate_email(value) {
	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);
}

