// -----------------------------------------------------------------------------
// greentv spesifik
// -----------------------------------------------------------------------------

var greentv = jsutil.define_namespace('greentv');

globals.page_unload_captured = false;
globals.video_playing = false;
globals.page_unload_message = "Green.TV is currently playing.";
globals.default_video_to_play = '';
globals.mute_setting = false;
globals.fullscreen_setting = false;

var greentv_tabs = {
  'main': 'nav1',
  'info': 'nav2',
  'channels': 'nav3',
  'contacts': 'nav4',
  'community': 'Image28'
}

Object.extend(greentv, {

    selected_tab_image: 'nav1',

    clip_info: new Object(),

    queue_list: new Array(),

    played_list: new Array(),

    select_tab: function (name, autoswitch) {
      if (autoswitch == true) {
        io.toggle_tab(name);
        var current_tab = $.get(greentv.selected_tab_image);
        current_tab.highlighted = false;
        if (current_tab.oSrc)
          current_tab.src = current_tab.oSrc;
        var img_id = greentv_tabs[name];
        var img_ob = $.get(img_id);
        img_ob.highlighted = true;
        var img_src = img_ob.src;
        if (!img_src.endswith('_over.gif')) {
          img_ob.oSrc = img_ob.src;
          img_ob.src = img_src.replace('.gif', '_over.gif');
        }
        greentv.selected_tab_image = img_id;
      }
      // highlight tab
    },

    select_tab_on_load: function (name) {

      var loader = function () {
        greentv.select_tab(name, true);
      };

      return loader;

    },

    load_in_tab: function (tab, uri, autoswitch, parameters) {

        if (parameters == undefined)
            parameters = '';

        new Ajax.Updater(
            tab, uri,
            {method: 'get', parameters: parameters,
             onSuccess: function() {greentv.select_tab(tab, autoswitch);}}
            );

    },

	show_listings: function (tag, page) {

      greentv.load_in_tab('main', '/de/!site.listings/' + tag, true);
      greentv.load_in_tab('info', '/de/!site.tag_info/' + tag, false);
	  
	},

	load_community: function (page) {

      greentv.load_in_tab('community', '/de/!site.community_page/' + page, true);

	},

    load_community_handler: function (page) {

      var loader = function () {
        greentv.load_community(page);
      };
        
      return loader;                  

    },

	load_info: function (movie, autoswitch) {

      greentv.load_in_tab('info', '/de/!site.info/' + movie, autoswitch);

      return false;

	},

	show_info: function (movie) {

      greentv.load_info(movie, true);

	},

    do_search: function () {

      var query = encodeURIComponent($.get('query').value);
      greentv.load_in_tab('main', '/de/!site.search/' + query, true);

      return false;

    },


    get_listings_for_channel: function (channel) {
        globals.selected_channel = channel;
		Ajax.Updater();
	},

    get_listings_for_activity: function (activity) {
        if (!globals.selected_channel) {
		    var channel = '';
		} else {
		    var channel = globals.selected_channel;
		}
		Ajax.Updater();
	},

    handle_leaving_greentv: function () {
        // disconnect user from chat
        // var x = window.open('blah');
        // if( !x ) { alert('Please do not block popups on this site'); }
    },

    control_player: function (command, args) {

        var controller = globals.current_video_player_controller;

        if (command == 'setMute') {
          if (globals.mute_setting) {
            args = globals.mute_setting = false;
          } else {
            args = globals.mute_setting = true;
          }
        }

        controller[command](args);

          /*    
      try {
        var controller = globals.current_video_player_controller;
        controller[command](args)
      } catch (e) {
      }
          */

    },

    fullscreen: function () {

      try {

          var content = $.get('video-content');
          var controller = globals.current_video_player_controller;
          // var fullscreen_button = $.get('exit-fullscreen');

          if (globals.fullscreen_setting) {
              globals.fullscreen_setting = false;
              $.get('video-player-header').style.display = 'block';
              $.get('sidebar').style.display = 'block';
              $.get('video-player-footer').style.display = 'block';
              $.get('partners').style.display = 'block';
              $.get('beta-text').style.display = 'block';
			  $.get('seekbar-container').style.display = 'block';
			  $.get('banner_ad').style.display = 'block';
			  $.get('fullscreen-toggle').style.display = 'none';
              // $.get('inner-container').style.marginLeft = 'auto';
              content.style.borderLeft = '2px solid #85aa7f';
              content.style.borderRight = '2px solid #85aa7f';
              /*
              content.style.position = 'relative';
              content.style.display = 'block';
              content.style.width = '';
              content.style.height = '289px';
              content.style.zIndex = '200';
              content.style.top = '0px';
              content.style.left = '0px';
              content.style.marginLeft = '0px';
              fullscreen_button.style.display = 'none';
              */
              controller.setSize(512, 288);
          } else {
              globals.fullscreen_setting = true;

              $.get('video-player-header').style.display = 'none';
              $.get('sidebar').style.display = 'none';
              $.get('video-player-footer').style.display = 'none';
              $.get('partners').style.display = 'none';
              $.get('beta-text').style.display = 'none';
              $.get('seekbar-container').style.display = 'none';
			  $.get('banner_ad').style.display = 'none';
			  $.get('fullscreen-toggle').style.display = 'block';
              // $.get('inner-container').style.marginLeft = '0px';
              content.style.borderLeft = '0px';
              content.style.borderRight = '0px';
              /*
              content.style.position = 'absolute';

              content.style.display = 'block';
              content.style.width = '1024px';
              content.style.height = '576px';
              content.style.zIndex = '200';
              content.style.top = '-15px';
              content.style.left = '-512px';
              content.style.marginLeft = '50%';
              fullscreen_button.style.display = 'block';
          */
              controller.setSize(1024, 576);
          }

      } catch (e) {
      }

    },

    add_to_queue: function (name, at_start) {

        if (at_start) {
            var update_position = 0;
        } else {
            var update_position = greentv.queue_list.length;
        }

        if (!greentv.queue_list.has_item(name)) {

            if (name in greentv.clip_info) {
                greentv.queue_list.splice(update_position, 0, [name]);
                log("QUEUE: ");
                log(greentv.queue_list);
            } else {
                new Ajax.Request(
                   '/de/!site.get_available_videos/'+encodeURIComponent(name),
                    {method: 'get', onSuccess: functional.partial(greentv.save_clip_info, name, update_position, false)}
                );
            }

        }

    },

    save_clip_info: function (name, update_position, insert_before, transport, json) {

        // eval("var options = "+transport.responseText);
        eval(transport.responseText);

        var supported = browser.get_supported_video_players();
        var available = new Array();

        for (var i=0; i < supported.length; i++) {
            var option = supported[i];
            if (options[option])
                available.push(option);
        }

        if (!available.length) {
             alert("Sorry, no appropriate players were detected. Please see the manual download links on the right.");
             greentv.clip_info[name] = null;
             return;
        }

        if (play_before.length) {
            play_before = play_before[0];
            greentv.queue_list[update_position] = name;
            update_position += 1;
            new Ajax.Request(
                '/de/!site.get_available_videos/'+encodeURIComponent(play_before),
                {method: 'get', onSuccess: functional.partial(greentv.save_clip_info, play_before, update_position-1, true)}
            );
            // 'asynchronous': false, 
        } else {
            play_before = null;
        }

        log("AVAILABLE: "+name);
        log(available);

        if (globals.default_video_player == 'auto') {
            var best_option = available[0];
        } else {
            var best_option = globals.default_video_player;
        }

        var video_url = options[best_option][0];
        var video_duration = options[best_option][1];

        greentv.clip_info[name] = [best_option, video_url, video_duration, play_before, play_after];

        if (insert_before) {
            greentv.queue_list[update_position] = name;
        } else {
            greentv.queue_list.splice(update_position, 0, [name]);
        }

        if (play_after.length) {
            play_after = play_after[0];
            update_position += 1;
            new Ajax.Request(
                '/de/!site.get_available_videos/'+encodeURIComponent(play_after),
                {method: 'get', onSuccess: functional.partial(greentv.save_clip_info, play_after, update_position, false)}
            );
        } else {
            play_after = null;
        }

        log("QUEUE: ");
        log(greentv.queue_list);
        // greentv.do_actual_video_play(name, force, info);

    },

    play_video: function (name, force) {

        if (name == undefined) {
            name = globals.default_video_to_play;
        }

        if (!name)
            return;

        greentv.add_to_queue(name, true);
        setTimeout(functional.partial(greentv.play_next, force), 1000);

    },

    play_next: function (force) {

      if (greentv.queue_list.length) {
          name = greentv.queue_list.shift();
          greentv.played_list.push(name);
          greentv.do_actual_video_play(name, force);
      }

    },

    play_previous: function (force) {

      if (greentv.played_list.length) {
          var current = greentv.played_list.pop();
          var prev = greentv.played_list[greentv.played_list.length-1];
          greentv.queue_list.unshift(current);
          greentv.do_actual_video_play(prev, force);
      }

    },

    do_actual_video_play: function (name, force) {

      if (globals.video_playing && (!force))
          return;

      var controller = globals.current_video_player_controller;

      if (controller)
          try {
              controller.pause();
          } catch (e) {
          }

      var info = greentv.clip_info[name];

      log(info);

      if (info == null)
          return;

      controller = globals.current_video_player_controller = browser.get_video_player_controller(info[0]);

      globals.video_playing = true;
      controller.load(info[1], info[2]);

      time.sleep(1000);
      controller.play();

      return true;

    }


});

function log (msg) {
  if (globals.debug) {
    jsutil.debug.write(msg);
  } else {
  }
};

// -----------------------------------------------------------------------------
// player related
// -----------------------------------------------------------------------------

handleSeekBarChange=function(pos){
    try{
        var controller = browser.get_video_player_controller();
        controller.seek(controller.getDuration() * pos);
    }catch(e){
        log(e);
    }
};

setSeekBarPos=function(pos){
    var btn = document.getElementById("seek-button");
    var btnWidth=btn.offsetWidth;
    var barWidth=document.getElementById("seekbar").offsetWidth;
    
    btn.style.left =  (barWidth-btnWidth) * pos + "px";
};

setProgress=function(p){
    var barWidth=document.getElementById("seekbar").offsetWidth;
    var pr = document.getElementById("progress");
    pr.style.width = (barWidth * p / 100) + "px";
};


handleBarDown =function(evt){
    updateSeekButton(evt);
    //let's use Function 1. we don't get leeks in IE and 2. we can wrap the event object.
    document.onmousemove=new Function("evt", "handleBarMove(evt != null? evt : event);return false;");
    document.onmouseup=new Function("evt", "handleBarUp(evt != null? evt : event);return false");
};

handleBarMove=function(evt){
    //make sure that the mouse id down while dragging
    if(evt.button==0){
        document.onmousemove="";
        document.onmouseup="";
    }else{
        updateSeekButton(evt);
    }
    
};

handleBarUp =function(evt){
    updateSeekButton(evt);
    document.onmousemove="";
    document.onmouseup="";
};


updateSeekButton=function(evt){
    var btn = document.getElementById("seek-button");
    var btnWidth=btn.offsetWidth;
    var barWidth=document.getElementById("seekbar").offsetWidth;
    var x = evt.clientX - document.getElementById("seekbar").offsetLeft 
    x = x - btnWidth/2;
    
    if(x  > barWidth - btnWidth){
        x= barWidth-btnWidth;
    }
    if(x <  0){
        x=0;
    }
    btn.style.left=x+"px";
    handleSeekBarChange( x / (barWidth - btnWidth));
};



jsutil.event.add_load_event(io.setup_tab_toggle);
jsutil.event.add_load_event(io.setup_dynamic_labels);
jsutil.event.add_load_event(greentv.play_video);
// jsutil.event.add_load_event(browser.embed_player);

/*
window.onbeforeunload = function (evt) {
    globals.page_unload_captured = true;
    if (globals.video_playing) {
        evt.returnValue = globals.page_unload_message;
        return globals.page_unload_message;
    }
};
*/

window.onunload = function(evt) {
    greentv.handle_leaving_greentv();
    if (!globals.page_unload_captured) {
//         if (confirm('Foo')) {
//             return false;
//         } else {
//             return true;
//         }
    }
};

jsutil.event.add_load_event(io.setup_tab_toggle);

// -----------------------------------------------------------------------------
// shitty js from dreamweaver
// -----------------------------------------------------------------------------

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
    if (!x.highlighted)
      x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;
  if(!d) d=document;
  if(!(x=d[n])&&d.all) x=d.all[n];
  for (i=0;!x&&i<d.forms.length;i++)
    x=d.forms[i][n];
  if(!x && d.getElementById)
    x=d.getElementById(n);
  return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null) {
     if (!x.highlight) {
       document.MM_sr[j++]=x;
       if(!x.oSrc)
         x.oSrc=x.src;
       x.src=a[i+2];
     }
   }
}
// 'foo.gif'.replace('.gif', '_over.gif');
jsutil.event.add_load_event(functional.partial(MM_preloadImages, 'http://www.green.tv/static/images/controls/fullScreen_over.png', 'http://www.green.tv/static/images/controls/muteOn_over.png', 'http://www.green.tv/static/images/controls/next_over.png', 'http://www.green.tv/static/images/greentv/listbox/post_channels/listBox1_over.gif','http://www.green.tv/static/images/greentv/listbox/post_channels/listBox2_over.gif','http://www.green.tv/static/images/greentv/listbox/post_channels/listBox3_over.gif','http://www.green.tv/static/images/greentv/listbox/post_channels/listBox4_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav1_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav2_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav3_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav4_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav5_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav6_over.gif','http://www.green.tv/static/images/greentv/vidarea/vNav7_over.gif','http://www.green.tv/static/images/greentv/vidarea/filter1_over.gif','http://www.green.tv/static/images/greentv/vidarea/filter2_over.gif','http://www.green.tv/static/images/greentv/vidarea/filter3_over.gif','http://www.green.tv/static/images/controls/previous_over.png','http://www.green.tv/static/images/controls/play_over.png','http://www.green.tv/static/images/controls/pause_over.png','http://www.green.tv/static/images/greentv/listbox/post_channels/listBoxBot_over.gif'));


