var UI = window.UI||{};
var App = window.App||{};
var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
try {document.execCommand("BackgroundImageCache", false, true);} catch(e) {}

function when(obj, fn) {
  if (Object.isString(obj)) obj = /^[\w-]+$/.test(obj) ? $(obj) : $(document.body).down(obj)
  if (Object.isArray(obj) && !obj.length) return
  if (obj) fn(obj)
}

Element.addMethods('input', {
  defaultValueActsAsHint: function(element){
    element = $(element);
    element._default = element.value;
    return element.observe('focus', function(){
      if(element._default != element.value) return;
      element.removeClassName('hint').value = '';
    }).observe('blur', function(){
      if(element.value.strip() != '') return;
      element.addClassName('hint').value = element._default;
    }).addClassName('hint');
  }
});

Element.addMethods({
  makeInvisible : function(element){
    return $(element).setStyle({
      'visibility' : 'hidden'
    });
  },
  makeVisible : function(element){
    return $(element).setStyle({
      'visibility' : 'visible'
    });
  }
});

if(!String.prototype.uncache){
  Object.extend(String.prototype, {
    uncache : function(){
      return this+((this.indexOf('?')!=-1) ? '&' : '?')+'uncache='+new Date().getTime();
    }
  });
}

Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
  initialize: function(element, delay, callback) {
    this.delay     = delay || 0.5;
    this.element   = $(element);
    this.callback  = callback;
    this.timer     = null;
    this.lastValue = $F(this.element);
    Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  },
  delayedListener: function(event) {
    if(this.lastValue == $F(this.element)) return;
    if(this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
    this.lastValue = $F(this.element);
  },
  onTimerEvent: function() {
    this.timer = null;
    this.callback(this.element, $F(this.element));
  }
};

App.AssetViewer = Class.create({
  initialize : function(element){
    this.element = $(element);
    this.id = this.element.up('div.tab').identify();
    this.path = this.id == 'wallpapers' ? 'wallpaper' : this.id;
    this.ul = this.element.down('ul');
    this.build();
    this.loaded = {};

    this.carousel = new UI.Carousel(this.element, {
      onScroll : this.onScroll.bind(this)
    });
  },
  build : function(){
    var data = this.data = $A(window[this.id]);
    this.lis = this.ul.childElements();

    if(data){
      this.lis[this.lis.size()-1].removeClassName('last-child');
      for(var i=0; i<data.length; i++){
        this.ul.insert(new Element('li', {style:'width:221px;height:173px;'}).insert(new Element('a', {className: 'lightbox', rel: this.id, href: 'http://www.thq.com/resources/'+this.path+'/large/'+data[i].filename})));
      }
      this.lis = this.ul.select('li');
      this.lis[this.lis.size()-1].addClassName('last-child');
    }
    this.lis = this.ul.childElements();
  },
  onScroll : function(){
    var index = Math.max(Math.ceil(this.carousel.get_offset(this.carousel.offset)/221)-1, 0);
    if(!this.loaded[index]){
      this.loadOne(index);
    }
    this.loadSiblings(index);
  },
  loadSiblings : function(index){
    if(index>0){
      for(var i=index-1; i>index-4; i--){
        this.loadOne(i);
      }
      for(var i=index+1; i<index+4; i++){
        this.loadOne(i);
      }
    }
  },
  loadOne : function(index){
    if(!this.loaded[index] && this.data[index]){
      var element = this.create(this.data[index]);
      this.lis[index+3].down().insert(element);
      this.loaded[index]=true;
    }
  },
  create : function(data){
    var element = new Element('img', {alt: data.title, src: 'http://assets.thqonline.net/'+this.id+'/medium/'+data.thumbfilename, width: '203', height: '152'});
    return element;
  }
});

App.GameRegistration = function(){
  var element, input, list, names;

  function filter(element, value){
    value = value.toLowerCase();
    names.each(function(name, i){
      Element[(name.indexOf(value)!=-1 ? 'show' : 'hide')](list[i]);
    });
  }

  return {
    initialize : function(element){
      element = $(element);
      input = element.down('input[type=text]');
      list = element.select('ul li');
      names = element.select('ul li label').map(function(name){
        return name.innerHTML.toLowerCase();
      });
      new Form.Element.DelayedObserver(input, 0.5, filter);
    }
  }
}();

App.Updates = Class.create({
	initialize : function(element, options) {
		this.element = $(element);
		this.options = Object.extend({
			offset : 100
		}, options||{});
		this.locked = false;
		this.viewPort = this.element.select('div.module-bd').first();
		this.viewPortHeight = this.viewPort.offsetHeight - parseInt(this.viewPort.getStyle('padding-top'), 10) - parseInt(this.viewPort.getStyle('padding-top'), 10);
		this.ul = this.viewPort.select('ul').first();
		this.ul.style.marginTop=0;
		this.height = this.ul.offsetHeight;
		this.maxOffset = this.viewPortHeight;
		this.addListeners();
	},
	addListeners : function(){
		var prev = this.element.select('a.prev').first(); //.observe('click', this.scroll.bindAsEventListener(this));
		var next = this.element.select('a.next').first(); //.observe('click', this.scroll.bindAsEventListener(this));

		prev.observe('mouseenter', this.startScrolling.bindAsEventListener(this, 'prev'));
		prev.observe('mouseleave', this.stopScrolling.bindAsEventListener(this));
		prev.observe('click', function(e){e.stop();});
		next.observe('mouseenter', this.startScrolling.bindAsEventListener(this, 'next'));
		next.observe('mouseleave', this.stopScrolling.bindAsEventListener(this));
		next.observe('click', function(e){e.stop();});
	},
	startScrolling : function(e, direction){
	  var position = parseInt(this.ul.style.marginTop);
	  if(direction=='prev'){
	    var anim = -(this.height-this.maxOffset);
	    var speed = (position-anim)/this.maxOffset;
	  }else{
	    var anim = 0;
	    var speed = (-position)/this.maxOffset;
	  }

	  var str = 'margin-top:'+anim+'px;'
    this.animation = new Effect.Morph(this.ul, {
      style : str,
      'duration' : speed*2,
      'queue' : 'end',
      afterFinish : function(){
        this.locked = false;
      }.bind(this)
    });

	},
	stopScrolling : function(e){
	  this.animation.cancel();
	},
	scroll : function(e){


/*    var anim, property;
    Event.stop(e);
    if(this.locked===false){
      this.locked = true;
      var direction = Event.element(e).className.split(' ')[0];
      if(direction=='prev'){
        anim=parseInt(this.ul.style.marginTop)-(this.options.offset*1);
        if(-anim>parseInt(this.height)-this.maxOffset){
          anim=-(parseInt(this.height)-this.maxOffset);
        }else{
          this.index = this.index+1;
        }
      }else if(direction=='next'){
        anim=parseInt(this.ul.style.marginTop)+(this.options.offset*1);
        if(anim>0){
          anim=0;
        }else{
          this.index = this.index-1;
        }
      }
      var str = 'margin-top:'+anim+'px;'
      new Effect.Morph(this.ul, {
        style : str,
        'duration' : 0.5,
        'queue' : 'end',
        afterFinish : function(){
          this.locked = false;
        }.bind(this)
      });
    }*/
	}
});


App.LoginBox = function(){
  var button, box, close, email, mythq;

  function show(e){
    e.stop();
    new Effect.Fade(mythq, {
      'queue' : 'end',
      'duration' : 0.25
    });
    new Effect.BlindDown(box, {
      'queue' : 'end',
      'afterFinish' : function(){
        email.focus();
      }
    });
  }

  function hide(e){
    e.stop();
    new Effect.BlindUp(box, {
      'queue' : 'end'
    });
    new Effect.Appear(mythq, {
      'queue' : 'end',
      'duration' : 0.25
    });
  }

  return {
    initialize : function(){
      button = $('signin-button');
      box = $('login-box');
      close = $('login-close');
      email = $('login_email');
      mythq = $('mythq-links');

      button.observe('click', show);
      close.observe('click', hide);
    }
  }
}();

App.Navigation = function(){

  var element, hover, selected, t=null, _t=null;

  function onMouseEnter(e){
    var element;
    if(element = e.findElement('li.nav')){
      if(t && _t){
        _t();
        window.clearTimeout(t);
        t = _t = null
      }
      element.addClassName('hover');
      hover = element;
    }
  }

  function onMouseLeave(e){
    if(hover){
      _t = function(){
        hover.removeClassName('hover');
      };
      t = window.setTimeout(_t, 500);
    }
  }

  return {
    initialize : function(){
      element = $('navigation');
      element.select('li.nav').each(function(tab){
        tab.observe('mouseenter', onMouseEnter);
        tab.observe('mouseleave', onMouseLeave);
      });




    }
  }
}();


App.Tooltips = function(){
  var _initialized, animating = false, parent, tooltip, tooltips = {}, visible = false, w = 290;

  function initialize(){
    tooltip = new Element('div', {
      className : 'tt'
    }).setStyle({
      position: 'absolute',
      zIndex: 200
    }).update('<div class="t"><div></div></div><div class="l"><div class="r"><div class="c"><a href="#" class="close">close</a><div class="i"></div></div></div></div><div class="f"><div></div></div>');
    tooltip_c = tooltip.down('.c')
    tooltip_i = tooltip_c.down('.i');
    tooltip_a = tooltip_c.down('a.close');
    tooltip_a.hide();
    tooltip_a.observe('click', hide_tooltip);

    ((parent) ? parent : $$('body').first()).insert({bottom: tooltip});
    _initialized = true;
  }

  function hide(callback){
    tooltip_a.hide();
    new Effect.Morph(tooltip_c, {
     style : {
       height: '0px',
       width: '0px'
     },
     duration: 0.5,
     afterFinish : (callback||Prototype.emptyFunction).wrap(function(original){
       animating = false;
       visible = false;
       return original();
      })
    });
  }

  function hide_tooltip(e){
    e.stop();
    if(visible && !animating){
      hide(function(){
        tooltip.hide();
      });
    }
  }

  function show(element, content){
    tooltip.show();
    tooltip_i.update(content);
    var h = tooltip_i.offsetHeight;
    var screen = document.viewport.getDimensions();
    var pos = element.cumulativeOffset();
    var lw = pos.left+w;
    var r = (lw>screen.width) ? screen.width-pos.left-element.offsetWidth+'px' : 'auto';
    var l = (lw>screen.width) ? 'auto' : pos.left+'px';
    tooltip.setStyle({
      left: l,
      top: pos.top+'px',
      right: r
    });
    new Effect.Morph(tooltip_c, {
      style : {
        height: h+'px',
        width: w+'px'
      },
      duration : 0.5,
      afterFinish : function(){
        animating = false;
        visible = true;
        tooltip_a.show();
      }
    });
  }

  function show_tooltip(e){
    e.stop();
    var element = e.findElement('.tooltip');
    var content = tooltips[element.identify()];
    if(content){
      if(visible){
        hide(show.curry(element, content));
      }else{
        show(element, content);
      }
    }
  }

  return {
    add_tooltip : function(element, content){
      if(!_initialized) initialize();
      var element = $(element);
      tooltips[element.identify()] = content;
      element.observe('click', show_tooltip);
    }
  }
}();

function logMissingTranslation(text, locale){
  var url = '/missing-translation.php?locale='+locale+'&text=TESTER';
  var img = new Image();
  img.src = url;


/*  new Ajax.Request('/missing-translation.php', {
    method : 'post'
    parameters : {
      'text' : text,
      'locale' : locale
    }
  });*/
}


App.Popup = Class.create(UI.Modal, {
  initialize : function($super, selector, element, options){
    this.element = $(element);
    this.selector = selector;
    options = Object.extend({
      modalClassName : 'popup',
      width: '344'
    }, options || {});
    $super(options);
  },
  build : function($super){
    $super();
    this.content.insert(this.element);
  },
  show : function(skip){
    this.content.style.overflow='hidden';

    if(!skip){
	    $$('.ui-hide').invoke('makeInvisible');
	  }

    this.viewport = document.viewport.getDimensions();
    this.wrapper.setStyle({'height' : Math.max(this.root.getHeight(), this.viewport.height)+'px'});

    this.contentOuter.setStyle({'opacity' : 1}).show();
    this.close.setStyle({'opacity' : 1}).show();

    this.wrapper.setStyle({
      'opacity' : 0
    }).show();

    this.setLayout(this.getLayout());
    new Effect.Opacity(this.wrapper, {
      'from' : 0,
      'to' : 1,
      'duration' : 0.25,
      'queue' : 'end',
      'afterFinish' : function(){
        this.visible = true;
      }.bind(this)
    });

    //this.content.style.overflow='';

	  return this;
  },
  hide : function(){
    $$('.ui-hide').invoke('makeVisible');
    new Effect.Opacity(this.wrapper, {
      'from' : 1,
      'to' : 0,
      'duration' : 0.25,
      'queue' : 'end',
      'afterFinish' : function(){
        this.wrapper.hide();
        this.visible = false;
        this.p = this.d = null;
      }.bind(this)
    });
	  return this;
  }
});

App.EasterEgg = function(){
  var image;
  var konami = '38,38,40,40,37,39,37,39,66,65,13';
  var keys = [];
  var duck = '/img/site/layout/duck.png';
  var visible = false;

  function fire(){
    var dimensions = document.viewport.getDimensions();
    var d = image.getDimensions();
    var x = Math.max(0, Math.floor(Math.random()*dimensions.width)-d.width);
    var y = Math.max(0, Math.floor(Math.random()*dimensions.height)-d.height);

    if(!visible){
      image.setStyle({
        'left' : x+'px',
        'top' : y+'px'
      }).show();
      visible = true;
    }else{
      new Effect.Move(image, {
        'mode' : 'absolute',
        'x' : x,
        'y' : y,
        'duration' : 0.25
      });
    }
  }

  function onkeydown(e){
    keys.push(e.keyCode);
    if(keys.toString().indexOf(konami)>=0){
      fire();
      keys = [];
    }
  }

  return {
    initialize : function(){
      Event.observe(window, 'keydown', onkeydown);
      image = new Element('img', {src: duck}).setStyle({
        'position' : 'absolute',
        'zIndex' : 500
      }).hide();
      document.body.appendChild(image);
    }
  }
}();

function saveAgeGate(day, month, year){
  var url = '/services/agegate.php?dob_day='+day+'&dob_month='+month+'&dob_year='+year;
  var img = new Image();
  img.src = url;
  return true;
}

function SaveMoviePlay(id){

	var url = '/services/movieTracking.php?movieId='+id;
	var img = new Image();
	img.src = url;


}

function showAllVideos(){
  $$('div.hfeed').first().scrollTo();
}


function externalWarningFlash(href,type) {
  window.externalPopup.show(true);
  $('external-popup-yes').href = href;
}

App.SearchForm = function(){
  var age_rating, data, genre, genres, platform, platforms, release_date, selection;

  function updateDropDown(element, property, data, selection, selected){
    var s = selection.pluck(property).uniq();
    element.update(data.findAll(function(d){
      console.log(s.include(d[0]))
      return s.include(d[0]);
    }).inject('<option value="">Please select</option>', function(h, d){
      if(selected && selected==d[0]){
        return h+'<option value="'+d[0]+'" selected="selected">'+d[1]+'</option>';
      }
      return h+'<option value="'+d[0]+'">'+d[1]+'</option>';
    }));
  }

  function update(e){
    var a = $F(age_rating);
    var g = $F(genre);
    var p = $F(platform);
    var selection = data.findAll(function(d){
      var t = true;
      if(a){t = t && d.age_rating == a;}
      if(g){t = t && d.genre == g;}
      if(p){t = t && d.platform == p;}
      //if(r){t = t && d.platform == p;}
      return t;
    });

    updateDropDown(platform, 'platform', platforms, selection, p);
    updateDropDown(genre, 'genre', genres, selection, g);
    updateDropDown(age_rating, 'age_rating', age_ratings, selection, a);

  }

  function registerEvents(){
    age_rating.observe('change', update);
    genre.observe('change', update);
    platform.observe('change', update);
    release_date.observe('change', update);
  }

  return {
    initialize : function(){
      data = $A(window.games);
      age_rating = $('age_rating');
      age_ratings = age_rating.select('option').collect(function(e){
        return [parseInt(e.value, 10), e.innerHTML];
      });
      genre = $('genre');
      genres = genre.select('option').collect(function(e){
        return [parseInt(e.value, 10), e.innerHTML];
      });
      platform = $('platform');
      platforms = platform.select('option').collect(function(e){
        return [parseInt(e.value, 10), e.innerHTML];
      });
      release_date = $('release_date');
      registerEvents();
    }
  }
}();


document.observe("dom:loaded", function(){

  if(window.games && $('search-form')){
    App.SearchForm.initialize();
  }

  // Add CSS class name to body if javascript is available
  $$('body').first().addClassName('js');

   when('mythq', function(element){
    var options =  {
       trigger : '.title span',
       content : 'div.module-bd:not(.force)',
       closed : false
     };

     if($('personal_details')){
       options.closed = true;
     }

     if(window.location.hash){
       var hash = window.location.hash.substring(1);
       var hashes = $w('my-games register-a-game about-alerts my-alerts top-5 personal-details gaming-profile permissions delete-account');
       if(hashes.include(hash)){
         options.open = '.'+hash;
         options.closed = false;
       }else if(hash=='welcome' && $('welcome-popup')){
         var welcome = new App.Popup('.welcome', 'welcome-popup', {
           top : 164
         });
         welcome.show();
       }
     }

    new UI.Accordion(element, options);
  });

  when('keyw', function(element){
    element.defaultValueActsAsHint();
  });

  $$('.tabset').each(function(element){
    new UI.Tabset(element);
  });

  $$('.ui-carousel').each(function(element){
    new App.AssetViewer(element);
  });

  $$('.home-section .updates').each(function(element){
    new App.Updates(element);
  });

  App.Navigation.initialize();

  when('signin-button', function(element){
    App.LoginBox.initialize();
  });


  when('game-filter', function(element){
    App.GameRegistration.initialize(element);
  });

  new UI.AjaxModal('.modal', {
    modalClassName : 'popup faq',
    height: '400',
    width: '600'
  });
  new UI.Lightbox('.lightbox');

  $$('form div.tooltip').each(function(element){
    var l = element.previous('label');
    var html = (l) ? '<h3>'+l.innerHTML+'</h3>'+element.innerHTML : element.innerHTML;
    App.Tooltips.add_tooltip(element, html);
  });

  $$('div.mythq div.module-hd div.tooltip').each(function(element){
    App.Tooltips.add_tooltip(element, element.innerHTML);
  });

  if(locale=='us'){
    window.externalPopup = new App.Popup('.external', 'external-popup');
    var domains = $w('thq.localhost thq.com (.*).thq.com thq-games (.*).thq-games.com (.*).thq.co.uk thq.co.uk (.*).kenexa.com (.*).lawton-staging.co.uk (.*).thqonline.net (.*).esrb.org esrb.org').map(function(d){
      return new RegExp(d);
    });
    document.observe('click', function(e){
      var element = e.findElement('a');
      if(element){
        var href = element.getAttribute('href');
        var domain = element.hostname;
        if(href && domain){
          var external = domains.find(function(d){
            return domain.match(d);
          });
          if(!external){
            e.stop();
            window.externalPopup.show();
            $('external-popup-yes').href = href;
          }
        }
      }
    });
  }

  $('external-popup-no').observe('click', function(e){
    e.stop();
    window.externalPopup.hide();
  });

  $('external-popup-yes').observe('click', function(e){
    e.stop();
    var element = e.findElement('a');
    if(element){
      //document.location = element.href;
      window.open(element.href, 'THQ');
      window.externalPopup.hide();
    }
  });

  var host = window.location.hostname;
  if(host == 'thq.localhost' || host == 'thq-us-beta.lawton-staging.co.uk'){
    App.EasterEgg.initialize();
  }


});