// -----------------------------------------------------------------------------
// greentv spesifik
// -----------------------------------------------------------------------------

var greentv = {};//jsutil.define_namespace('greentv');

var globals = {};
globals.page_unload_captured = false;
globals.video_playing = false;
globals.current_video = '';
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) {
        this.toggle_tab(name);
        var current_tab = $(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 = $(img_id);
        img_ob.highlighted = true;
        var img_src = img_ob.src;
        if ( img_src.indexOf('_over.gif') < 0 ) {
          img_ob.oSrc = img_ob.src;
          img_ob.src = img_src.replace('.gif', '_over.gif');
        }
        greentv.selected_tab_image = img_id;
      }
      // highlight tab
    },

    toggle_tab: function (id) {

        $('sidebar-content').childElements().each(function(trigger){
            if( trigger.id != id )
                trigger.setStyle({ display : 'none'});
            else
                trigger.setStyle({ display : 'block'});
        });

    },

    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);
                    
                    uri_array = uri.split('/');
                    if (uri_array[uri_array.length-1]=='technologies'&&tab=='main') {
                        greentv.play_video('sting_technologies', true);
                    }
            }}
        );

    },

	show_listings: function (tag, page) {

      greentv.load_in_tab('main', '/!site.listings/' + tag, true);
      greentv.load_in_tab('info', '/!site.tag_info/' + tag, false);
	  
	},

	load_community: function (page) {

      greentv.load_in_tab('community', '/!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', '/!site.info/' + movie, autoswitch);

      return false;

	},

	show_info: function (movie) {

      greentv.load_info(movie, true);

	},

    do_search: function () {

      var query = encodeURIComponent($('query').value);
      greentv.load_in_tab('main', '/!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) {

        globals.user_has_clicked_button = true;
        

        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 = $('video-content');
          var controller = globals.current_video_player_controller;
          // var fullscreen_button = $.get('exit-fullscreen');

          if (globals.fullscreen_setting) {
              globals.fullscreen_setting = false;
              $('share-form-fullscreen-wrapper').style.display = 'block';
              $('video-player-header').style.display = 'block';
              $('sidebar').style.display = 'block';
              $('video-player-footer').style.display = 'block';
              //$.get('partners').style.display = 'block';
              $('beta-message-container').style.display = 'block';
	      $('seekbar-container').style.display = 'block';
	      $('banner_ad').style.display = 'block';
	      $('fullscreen-toggle').style.display = 'none';
              // $.get('inner-container').style.marginLeft = 'auto';
	      $('main-banner').style.display = 'block';
              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;
              $('share-form-fullscreen-wrapper').style.display = 'none';
              $('video-player-header').style.display = 'none';
              $('sidebar').style.display = 'none';
              $('video-player-footer').style.display = 'none';
              //$.get('partners').style.display = 'none';
              $('beta-message-container').style.display = 'none';
              $('seekbar-container').style.display = 'none';
			  $('banner_ad').style.display = 'none';
			  $('fullscreen-toggle').style.display = 'block';
              // $.get('inner-container').style.marginLeft = '0px';
	          $('main-banner').style.display = 'none';
              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('/!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(
                '/!site.get_available_videos/'+encodeURIComponent(play_before), {
                    method: 'get', 
                    onSuccess: functional.partial(greentv.save_clip_info, play_before, update_position-1, true)
                }
            ); 
        } else {
            play_before = null;
            setTimeout(functional.partial(greentv.play_next, true), 10);
        }

        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(
                '/!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, true);

    },

    play_video: function (name, force) {

        if (name == undefined) {
            name = globals.default_video_to_play;
        }

        if (!name)
            return;

        load_new(name);
//        player.play(name);
//        greentv.add_to_queue(name, true);
    
    },

    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) {
        
      log(" @@@@ doing actual video play: " + name);
      
      if (globals.video_playing && (!force))
          return;

      var controller = globals.current_video_player_controller;

      if (controller)
          try {
              controller.pause();
              controller.seek(0);
          } catch (e) {
      }

      var info = greentv.clip_info[name];

      log("INFO!!!:");
      log(info);

      if (info == null)
          return;

      controller = globals.current_video_player_controller = browser.get_video_player_controller(info[0]);

      globals.video_playing = true;
      globals.current_video = name;
      controller.load(info[1], info[2]);

      globals.user_has_clicked_button = false;
      setTimeout(greentv.play_if_not_playing, 3000);

      time.sleep(1000);
      // controller.play();

      return true;

    },
    
    play_if_not_playing: function () {
        if (!globals.user_has_clicked_button) {
            var controller = globals.current_video_player_controller;
            var raw_pos = controller.getPositionFromPlayer();
            var play_state = controller.getStateFromPlayer();
            log("raw_pos");
            log(raw_pos);
            log("play_state");
            log(play_state);
            
            var stuck_at_the_beginning = !!(raw_pos < 0.4);
            var loading = !!(play_state=="loading");
            var paused = !!(play_state=="paused");
            if (stuck_at_the_beginning || loading || paused) {
                log("Forcing it to play");
                controller.play();
            }
        }
    },
    
    share_video: function (name) {
      var video_id;
      if (name) {
        video_id = name;
      }
      else {
        video_id = globals.current_video;
      }

      new Ajax.Request('/!site.get_title/' + encodeURIComponent(video_id), {
          'method': 'get', 
          'onSuccess': function (transport) {
            // update the form
            var id = video_id;
            var title = transport.responseText;

            share_form_handler.update(id, title);
            // show the form
            share_form_handler.open();
          }
        }
      );
    }

});

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));
};



document.observe(
    'dom:loaded', function(){
/* pire        io.setup_tab_toggle();
        io.setup_dynamic_labels();*/
        greentv.play_video();
});
/*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);
/* pire document.observe(
    'dom:loaded', function(){
        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'));
document.observe(
    'dom:loaded', function(){
        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');
    });

var functional = function () {

    var func = arguments[0];
    var ori_args = new Array();

    for (var i=1; i < arguments.length; i++) {
        ori_args.push(arguments[i]);
    }

    return {
        partial : function () {
    
            var new_args = new Array();
    
            for (var i=0; i < ori_args.length; i++)
                new_args.push(ori_args[i]);
    
            for (var i=0; i < arguments.length; i++)
                new_args.push(arguments[i]);
    
            return func.apply(this, new_args);
    
        }
    }

}