// Grab related functions

// helper to short console.log()
var log = function(msg){try { console.log(msg) } catch(error) {} }

jQuery.fn.cssCheckbox = function () {

	jQuery("input[@type='checkbox'] + label", this).each( function(){
			if ( jQuery(this).prev()[0].checked )
				jQuery(this).addClass("checked");
		})
		.hover( 
			function() { jQuery(this).addClass("over"); },
			function() { jQuery(this).removeClass("over"); }
		)
		.click( function() {
			jQuery(this)
				.toggleClass("checked")
				.prev()[0].checked = !jQuery(this).prev()[0].checked;
		})
		.prev().css({visibility:"hidden"});
}

jQuery.fn.tweak = function(){
  $(this).animate({left: "715px"}, 500).animate({left: "700px"}, 500);
  return this
}

// jquery RegEX plugin
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

// convert RGB to HEX
var RGBToHex = function (rgb) {
	var hex = [
		rgb.r.toString(16),
		rgb.g.toString(16),
		rgb.b.toString(16)
	];
	$.each(hex, function (nr, val) {
		if (val.length == 1) {
			hex[nr] = '0' + val;
		}
	});
	return hex.join('');
}

// Calculate the aspect ratio based upon a given width
var calculate = function(aspect) {
    var ratio = $(aspect).attr("rel") ;
    if (dimension == "width") height.value = ratio_int[1] * width.value / ratio_int[0];
    if (dimension == "height") width.value = ratio_int[0] * height.value / ratio_int[1];
}

// insert code into textarea ::
var applyToEmbed = function(code){
  $("#code").html(code)
}

//	Synchronizes the Customization UI with the Experience options
var syncCustomizationsWithExperience = function(_exp){
    var aspect_ratio = Aspect.getRatio();
    _exp.options.update("ap", !!(Widget.auto_play) ? 1:0);
    _exp.options.update("aa", !!(Widget.auto_advance) ? 1:0);
    _exp.options.update("ar", aspect_ratio[0] + ":" +aspect_ratio[1]);
    _exp.options.update("w", +Widget.width);
    _exp.options.update("h", +Widget.height);
    _exp.options.update("theme", Widget.scheme);
    _exp.options.update("rc", +Widget.row_count);
    _exp.options.update("cc", +Widget.column_count);
    _exp.options.update("vic", +Widget.row_count * +Widget.column_count);
}

// check user type
var is_registered = function(user_type) { 
    if (user_type == "C") {
		$("#register").hide();
		$("#already_registered").show();
	}
}

// returns a CSS / HTML rgba Value ::
var rgba_code = function(rgba){
  var code = "rgba("
  $.each(rgba,function(i){ code+=rgba[i]; if(i<3) code+=","  })
  code += ")"
  return code
}


// Getter setter for playlist feed ::
var playlist = function(closure){
    // define somevariable to live in the closure of example
    if($("div.feed-list ul:first li:first a").length ==0) return
    var first =  Number($("div.feed-list ul:first li:first a").attr('id').replace('feed_',''))
    return {
      set:function(value){ first = value.replace('feed_',''); },
      get:function(value){ return first }
    }
}

// Create Custom Skin
var customSkin = function(RGB){
  return {overrides:{player:{videoLoad:{overlay:{color:{text:[255,255,255,1],overlayBackground:[RGB.r,RGB.g,RGB.b,0.65]}}},timecode:{color:{current:[0,0,0,1],total:[204,204,204,1]}},text:{color:{primary:[255,255,255,1],form:[0,0,0,1],alert:[255,0,0,1],secondary:[204,204,204,1],viewerMessage:[0,0,0,1]}},seekbar:{color:{download:[77,77,77,1],background:[RGB.r,RGB.g,RGB.b,0.65]}},tooltip:{color:{background:[245,243,163,1],text:[0,0,0,1]}},ui:{color:{stageBackground:[0,0,0,1],substageBackground:[102,102,102,1],formLine:[255,255,255,0],objectForeground:[255,255,255,1],objectBackground:[0,0,0,1],overlayBackground:[RGB.r,RGB.g,RGB.b,0.65],formBackground:[170,170,170,1],objectForegroundHighlight:[255,255,255,1],objectBackgroundHighlight:[RGB.r,RGB.g,RGB.b,0.65],accentLine:[255,255,255,1]}}}},key:"GRAB NETWORKS (default)"}
}

// calls and closes micro player
var micro_player = function(micro) {
  var $micro = $("#microPlayer");
  var default_guid = $("li.here div.feed_items dl:first dt:first").attr("lang");
  if(micro.play){
    var top =  ($(window).height() - $micro.height() ) / 2+$(window).scrollTop() ;
    var left = ($(window).width() - $micro.width() ) / 2+$(window).scrollLeft() ;
    $micro.css({'visibility':'visible','top': top, 'left' : left });
  try { 
      document.getElementById('micro').pauseVideo(); 
      document.getElementById('micro').loadNewVideo(String(micro.guid || default_guid));
      document.getElementById('micro').playVideo();
    } catch(err) { log("pause, load, play:"+err);  }
  } else {
    try {document.getElementById('micro').stopVideo()} catch(err) { log("stop video:"+err) }
    $micro.css({'left':-10000,'bottom':0});
  }
  
}


//	Update the client's embed code text that appears in the copy textfield
var updateCopyableEmbedCode = function(){
	var embed_code, component_context = GRABNETWORKS.publisher.context;
	
	// determine what embed code template to construct
	if (component_context == "single-player"){
		embed_code = Widget.getEmbedCode();
	} else {
		var experience = GRABNETWORKS.publisher.core.registry[0];
		embed_code = '<script type="text/javascript" id="' + experience.pubkey + '" src="' + experience.getUrl() + '"></script>';
	}
	
	//	update the textarea with the embed code
	$("#code").val(embed_code);
	return embed_code;
}


// on w/h change, rest size list
var reset_size_list = function(el){
  $(el).find("ul.dropdown>li:first-child")
}

// Returns RGBa code
var RGBa = function(rgba){
  return "rgb("+rgba[0]+","+rgba[1]+","+rgba[2]+","+rgba[3]+")"
} 


// Set Category Single Player video title, desc  on api call ::
var video_metadata = function(player){
  var title = String(document.getElementById(player).videoTitleText());
  var summary = String(document.getElementById(player).videoDescriptionText());
  $("#video_player_title").text(title)
  $("#video_player_summary").text(summary)
}

// Submit search form
var submit_search_form = function() { $("#search_form").submit(); }


// Advanced search related JS functions
var toggle_search_options = function() {
  $("#search_drawer").toggle();    
  if($("#search_drawer").hasClass('on')) {
    $("#search_options_button").removeClass('on');
  } else {
    $("#search_options_button").addClass('on');
  }

}

var submit_advanced_search_form = function() {
  $("#advanced_search_form").submit();
}

var reset_advanced_search = function() {
  $("#advanced_search_form input[name^='search'],#advanced_search_form select[name^='search']").val("");
  $ ("#selected_affiliates").text("")
}

var update_selected_affiliates_display = function() {
  var providers_html = "";  
  $("#as_all_providers option:selected").each(function () {
    providers_html += $(this).text() + "<BR>";
  });
    
  $("#selected_affiliates").html(providers_html);
}

var as_all_providers_changed = function(event) {
  clear_selections_for_all();
  update_selected_affiliates_display();
}

var as_AG_providers_changed = function(event) {  
  clear_selections_for_range(/^[A-Ga-g]/);
  record_provider_selections('ag');
  update_selected_affiliates_display();
}

var as_HM_providers_changed = function(event) {  
  clear_selections_for_range(/^[H-Nh-m]/);
  record_provider_selections('hm');
  update_selected_affiliates_display();
}

var as_NS_providers_changed = function(event) {  
  clear_selections_for_range(/^[N-Sn-s]/);
  record_provider_selections('ns');
  update_selected_affiliates_display();
}
var as_TZ_providers_changed = function(event) {  
  clear_selections_for_range(/^[T-Zt-z]/);
  record_provider_selections("tz");
  update_selected_affiliates_display();
}

var clear_selections_for_all = function(){
  $("#as_ag_providers option").each(function () {
    $(this).attr('selected',''); 
  });
  $("#as_hm_providers option").each(function () {
    $(this).attr('selected',''); 
  });
  $("#as_ns_providers option").each(function () {
    $(this).attr('selected',''); 
  });
  $("#as_tz_providers option").each(function () {
    $(this).attr('selected',''); 
  });
}


var clear_selections_for_range = function(selector){
  $("#as_all_providers option").filter(function () {
    return $(this).text().match(selector);  
  }).each(function () {        
    $(this).attr('selected','');        
  });
}

var record_provider_selections = function(range) {
  $("#as_"+range+"_providers option:selected").each(function () {
    selected_value = $(this).val();
    $("#as_all_providers option").each(function () {
      if(selected_value == $(this).val()){
       $(this).attr('selected','selected');
      }      
    });
  });
}

var reset_provider_view =  function() {
  $('#as_all_providers').hide();
  $('#as_ag_providers').hide();
  $('#as_hm_providers').hide();
  $('#as_ns_providers').hide();
  $('#as_tz_providers').hide();

  $('#as_all_providers_link').show();
  $('#as_ag_providers_link').show();
  $('#as_hm_providers_link').show();
  $('#as_ns_providers_link').show();
  $('#as_tz_providers_link').show();
  
  $('#as_all_providers_label').hide();
  $('#as_ag_providers_label').hide();
  $('#as_hm_providers_label').hide();
  $('#as_ns_providers_label').hide();
  $('#as_tz_providers_label').hide();
}

var show_as_all_providers = function() {
  reset_provider_view();
  $('#as_all_providers_link').hide();
  $('#as_all_providers_label').show();
  $('#as_all_providers').show();
}

var show_as_AG_providers = function() {
  reset_provider_view();
  $('#as_ag_providers_link').hide();
  $('#as_ag_providers_label').show();
  $('#as_ag_providers').show();
}

var show_as_HM_providers = function() {
  reset_provider_view();
  $('#as_hm_providers_link').hide();
  $('#as_hm_providers_label').show();
  $('#as_hm_providers').show();
}

var show_as_NS_providers = function() {
  reset_provider_view();
  $('#as_ns_providers_link').hide();
  $('#as_ns_providers_label').show();
  $('#as_ns_providers').show();
}

var show_as_TZ_providers = function() {
  reset_provider_view();
  $('#as_tz_providers_link').hide();
  $('#as_tz_providers_label').show();
  $('#as_tz_providers').show();
}

var isIE7 = function() {
  return ($.browser.msie && $.browser.version == '7.0') ? true : false
}

var toggle_custom = function(){
  $('ul.options li:first').removeClass('selected');
  $('ul.options li:last').addClass('selected')
}

function handle_zoho(){  
  $.ajax({type:"POST",url:"/record_embed"})
}


