var ord = Math.random();
ord = ord * 10000000;
ord = Math.ceil(ord);
var DartZone = function(size, tile){
    document.write('<script type="text/javascript" src="http://ad.doubleclick.net/adj/rainbow.filmcritic/;kw=;sz='+size+';tile='+tile+';ord='+ord+'?"></script>');
}

jQuery(function ($) {
     var filmcritic;
     var config = {};
     function FilmCritic () {
         debug.info('Executing FilmCritic');
        // filmcritic does have a constructor that should only be used once
        this.init   = function(options) {
            var cfg      = {
                debugMode          : 0,
                aboutThisFilmWidget: 0,
                FilmAMGID          : 0
            };
            var defaults = config;
            $.extend(config, options);
            this.enable('navmenus', 'li.mega');
            this.enable('ajax');
            $(".debug-msg").hide();
        };
        this.get      = function(key)      { return key ? config.key : config;  };
        this.set      = function(key, val) { config.key = val;                  };
        this.enable   = function(key, data){
            debug.info('Enabling '+key);
            this.set(key, true);
            var prop = this[key];
            var inited = '';
            if ((typeof prop == 'object') && (typeof prop['init'] == 'function')){
                debug.info('Initializing '+key);
                prop['init'](data);
                inited = ' and initialized';
            }
            debug.info('fc.enable: The filmcritic property '+key+' has been enabled'+inited);
        };
        this.disable  = function(key)      {
            this.set(key, false);
        };
        this.uncloak = function(el) {
            $(el).css({'display': 'block', 'opacity': 0}).animate({ opacity: 1.0 }, 2000);
        };

        this.ajax     = {
            init: function() {

                // $.each(
                //     ['ajaxSend', 'ajaxSuccess', 'ajaxError', 'ajaxComplete', 'ajaxStart', 'ajaxStop'],
                //     function() {
                //         $("#debug-panel").bind(this, this.eventHandler);
                //     }
                // );
                //
                // $.ajaxSetup({
                //     ajaxSend     : function() { this.eventHandler('ajaxSend');     },
                //     ajaxSuccess  : function() { this.eventHandler('ajaxSuccess');  },
                //     ajaxError    : function() { this.eventHandler('ajaxError');    },
                //     ajaxComplete : function() { this.eventHandler('ajaxComplete'); },
                //     ajaxStart    : function() { this.eventHandler('ajaxStart');    },
                //     ajaxStop     : function() { this.eventHandler('ajaxStop');     }
                // });
                // debug.info('fc.ajax.init: Ajax should be ready now');

            },
            eventHandler: function() {
                if ( ! fc.get('debugMode') ) return;

                $("#loading").bind("ajaxSend", function(){
                   $(this).show();
                 }).bind("ajaxComplete", function(){
                   $(this).hide();
                 });

                $("#debug-panel")
                  .ajaxSend(function(evt, request, settings){
                      $(this).append('<li>Starting AJAX request for '+settings.url+'</li>');
                  })
                  .ajaxSuccess(function(evt, req, settings){
                      $(this).append("<li>Successful Request!</li>");
                  })
                  .ajaxError(function(evt, req, settings, exception) {
                      $(this).append('<li>Error in AJAX request to '+settings.url+': '+exception);
                  })
                  .ajaxComplete(function(request, settings){
                      $(this).append("<li>Request Complete.</li>");
                  });

                $('#loader')
                  .ajaxStart(function(){
                      $(this).show();
                  })
                  .ajaxStop(function(){
                      $(this).hide();
                  });
            }
        };

        /*
         *  Nav menus
         */
        this.navmenus = {
            config: {
                interval:    50,
                sensitivity: 1,
                timeout:     250
            },
            init: function(sel, options) {
                // First merge the default settings with options from arguments
                var cfg      = {};
                var defaults = this.config;
                $.extend(cfg, defaults, options);
                // Initialize the callbacks for handling hover events
                cfg.over = this.add;
                cfg.out  = this.remove;
                debug.info('Initializing dropdown menus with '+
                           'the following configuration: ', cfg);
                // Make it go! Wheeeeee!
                $(sel).hoverIntent(cfg);
            },
            add:    function(){ $(this).addClass("hovering");    },
            remove: function(){ $(this).removeClass("hovering"); }
        };

        /*
         * Entry tags
         */
        this.entrytags = {
            init: function() {
                $("#alpha .entry-tags").each(function() {
                    var seen = {};
                    $("li", this).each(function() {
                        var t = $("a", this).text();
                        if ( typeof seen[t] == 'undefined' ) {
                            seen[t] = 1;
                        } else {
                            debug.debug('Hiding dupe entry tag: '+t);
                            $(this).hide();
                        }
                    })
                    // Adding comma to all visible but last
                    .filter(':visible').not(':last').each(function() {
                        var mkup = $(this).html();
                        if( $.trim(mkup).substr(-1) != "," ) { $(this).html(mkup+', '); }
                    });
                });
            }
        };

        /*
         * Star-based rating functions
         */
        this.starratings = {
            entries: [],
            boop: '',
            init: function() {
                $('#content .rating-widget-disabled')
                  .children("input:not(:radio)").hide()
                .end()
                  .stars({ disabled: true, split: 2 });

                entries = this.entries;
                if ( entries && entries.length ) {
                    debug.info('fc.starratings.init: We have '+entries.length+' entries to enstar');
                    var me = this;
                    $.each(entries, this.enstar);
                }

                $(".asset-rating").css('display', 'block').animate({ opacity: 1.0 }, 2000);
            },
            refreshUsersRating: function(data) {
                var eid   = data.eid;
                var amgID = data.amgID;
                var ratingBar = $("#ratings-"+eid);
                if ( data.rating ) {
                    var score = data.rating;
                    if ( score % 0.5 != 0 ) score = Math.round(score * 2) / 2;
                    $(".asset-rating-users .rating-widget-disabled", ratingBar)
                      .stars('select', score);
                    debug.info('Set entry '+eid+' equal to '+score);

                } else {
                    // Formulate and send request for latest rating
                    $.getJSON(
                        amgJsonURL+amgID,
                        function(data) {
                            var score = data.average;
                            if ( score % 0.5 != 0 ) score = Math.round(score * 2) / 2;
                            $(".asset-rating-users .rating-widget-disabled", ratingBar)
                              .stars('select', score);
                            debug.info('Set entry '+eid+' equal to '+score);
                        }
                    );
                    debug.info('Just sent request for rating for AMD ID '+amgID+' to '+amgJsonURL+amgID);
                }
            },
            enstar: function(i, data) {
                var eid = data.entryId;
                debug.info('fc.starratings.enstar: Enstarring entry ID '+eid);
                var amgID = data.amgId;
                var ratingBar = $("#ratings-"+eid);

                $(".rating-widget", ratingBar).each(function() {
                    debug.info(this);
                    // $(this).children().filter("input").not(":radio").hide()
                    $(this)
                      .children("input:not(:radio)").hide()
                    .end()
                      .stars({
                          split       : 2,
                          oneVoteOnly : true,
                          callback    : function(ui, type, value) {
                                // Formulate and send request
                                var ajaxdata = {
                                    "r"        : value,
                                    "entry_id" : eid,
                                    "amg_id"   : amgID
                                };
                                debug.dir(ajaxdata);
                                jQuery.ajax({
                                    url         : filmcriticRatingURL,
                                    type        : "POST",
                                    data        : ajaxdata,
                                    dataType    : "json",
                                    global      : false,
                                    success     : function(data, status, req){
                                                    debug.info('Rating posted:');
                                                    debug.dir(data);
                                                    if ((typeof data.error != 'undefined') && (data.error != '')) {
                                                        debug.error( data.error )

                                                    } else {
                                                        fc.starratings.refreshUsersRating({
                                                            'eid' : eid,
                                                            'amgID' : amgID,
                                                            'rating' : data.result.rating
                                                        });
                                                    }
                                                  },
                                    error       : function(req, status, err) {
                                                    debug.error('ERROR posting rating: '+err);
                                                    debug.debug({ 'req': req, 'status': status, 'err': err });
                                                  },
                                    complete    : function(data, status, req) {
                                                    // debug.info('The "complete" status was '+status);
                                                    // debug.dir(data);
                                                  }
                                });
                          }
                     });
                });
                if ( amgID == 0 ) {
                    debug.warn('NO AMG ID on entry ID '+eid);
                } else {
                    fc.starratings.refreshUsersRating({'eid' : eid, 'amgID' : amgID });
                }

            }
        };

        this.search = {
            init: function(el) { this.searchResultsDiv = el },
            displayItem: function(loc, num) {
                $.get(
                    window.fcBase.replace(/\/?$/, loc+'index.php'),
                    { search_index : 1, entry_summary : 1 },
                    function(data) {
                        $("#hit-"+num, this.searchResultsDiv).replaceWith(data);
                        if ( filmcritic.get('debugMode') )
                            debug.info("Entry %d: [%s]", num, loc);
                    }
                );
            }
        };

        /*
         * ON OUR RADAR widget
         */
        this.onourradar = {
            init: function() { filmcritic.uncloak('#onourradar'); }
        };

        // This was a valiant attempt to try to eliminate the observed latency from the blocking synchronous
        // call to teaser.js (the server must have been overloaded).  Unfortunately, because I didn't control
        // the other side, it was too difficult to get working.
        //
        // So, I leave it here for later when someone will surely need it...
        //
        // this.aboutthisfilm = {
            // init: function(data) {
                // if ( ! data ) return;
                // // http://movies.amctv.com/movie/40204/teaser.js
                // var aboutThisFilmWidget = $('#aboutthisfilm.widget');
                // var teaserHref          = "http://movies.amctv.com/movie/"+data.FilmAMGID+"/teaser.js";
                // debug.log("Loading About this Film data from "+teaserHref);

                // ATTEMPT #1 (worked but document.write killed the page)
                // $.ajax({
                //     url:        teaserHref,
                //     dataType:   'script',
                //     context:    aboutThisFilmWidget,
                //     success:    function (data, status) {
                //         debug.debug({'type': 'success', 'this': this, 'data': data, 'status': status});
                //     },
                //     error:      function (req, status, err) {
                //         debug.error('Could not load About this Film box');
                //         debug.debug({'type': 'error', 'this': this, 'err': err, 'status': status, 'req': req});
                //     },
                // });

                // ATTEMPT #2 (just completely failed because we're not getting HTML. WTF happened there?)
                // $("#teaser-js", aboutThisFilmWidget).load(teaserHref, function(response, status, req){
                //     debug.debug({'this': this, 'response': response, 'status': status, 'req': req});
                //     if ($(this).html() == '') {
                //         debug.error("About this Film data load failed for "+teaserHref);
                //     }
                //     else {
                //        debug.info("teaser.js is finished loading: "+$(this).html());
                //        $(aboutThisFilmWidget).slideDown('slow');
                //     }
                // });
            // }
        // };

        this.toprated = {
            domBase:        $('#alpha-inner'),
            init: function(data) {
                $('.idTabs-manual', this.domBase).idTabs();

                $('#critics-tab a', this.domBase).click(function(evt) {
                    evt.preventDefault();
                    document.location.hash = '#critics';
                    return false;
                });

                $('#users-tab a', this.domBase).click(function(evt) {
                    evt.preventDefault();
                    document.location.hash = '#users';
                    return false;
                });

                var activeTab = document.location.hash ? document.location.hash.substr(1)+'-tab' : '';
                if ( activeTab == 'users-tab' ) $('#users-tab a', this.domBase).click();

                $('table.toprated:has(tbody tr td)').each(function() {
                    $(this).tablesorter({
                        sortList: $(this).attr('id') == 'toprated-users' ? [[0,0]] : [[1,1]]
                    });
                });

            }
        };



/*
 // Commented out by Yoshitaka Ito on the 2011-02-04 to deal w/ architecture change for the Comingsoon Widget
        this.comingsoon = {
            films : [],
            add      : function(data) { this.films.push(data); },
            init     : function(f) {
                if ( this.films.length == 0 ) return;
                var myFilms = this.films;
                myFilms.sort(function(x, y) {
                    return [cmp(x.order, y.order), -cmp(x.pubdate, y.pubdate)] < [cmp(y.order, x.order), -cmp(y.pubdate,x.pubdate)] ? -1:1;
                });
                var showComingsoon = 0;
                $("#coming-soon-widget")
                  .find(".featured-item, li")
                  .each(function() {
                      if ( myFilms.length ) {
                          var item  = myFilms.shift();
                          if ( $(this).hasClass('featured-item') && item.thumbsrc ) {
                              $(".featured-item-asset img", this).attr('src', item.thumbsrc);
                          }
                          var inner = $(this).html();
                          // console.log('Working on: '+inner);
                          // console.log('Here comes the item:');
                          // console.dir(item);
                          $.each(item, function(k, v) {
                              // console.log('k: '+k);
                              // console.log('v: '+v);
                              if ( (v != '') || (k == 'hastrailer') ) {
                                  if ( k == 'release' && typeof v === 'object' ) {
                                      v = (v.getUTCMonth()+1)+'/'
                                            + v.getUTCDate()+'/'
                                            + v.getUTCFullYear();
                                  }
                                  inner = inner.replace(new RegExp(k.toLocaleUpperCase(), "g"), v);
                                  // console.log('Just replaced '+k.toLocaleUpperCase()+' with '+v);
                              }
                          });
                        // console.log('Converted to: '+inner);
                        $(this).html(inner);
                        showComingsoon = 1;
                    } else {
                        $(this).hide();
                    }
                    $(this).filter(".featured-item").find("img").each(function() {
                        $(this).show();
                    });
                })
                .end()
                .each(function() {
                    if ( showComingsoon ) $(this).show();
                });
            }
        };
*/        

        this.fade = function(el, args) {
            el = $(el);
            if ( el.length ) {
               if ( el.is(':visible') ) { el.fadeOut(args); } else { el.fadeIn(args); }
            }
        };

        this.obsoleteFn = function(stinky) {
            alert('Obsolete method invoked: '+stinky+'. See console for details');
            debug.warn('Obsolete method invoked', stinky);
            debug.trace('Obsolete method invoked');
        };

        delete FilmCritic; // disappear the constructor if you want
     }
     window.filmcritic = function () {
         return filmcritic || (filmcritic = new FilmCritic());
     };


	// Begin Review Trailers IVA
	// --------8<--------
	if (!$("div.widget-video-player").size()) $('link[rel=lucy-film-amg-id]').each(function(index) {

		// Identify the v_id from this element
		var v_id = false;
		if ($(this).attr('title'))
			v_id = $(this).attr('title');
		else if ($(this).attr('href'))
			v_id = $(this).attr('href');
		if (v_id === false)
			return;

		// Inject flash player support
		var head = document.getElementsByTagName('head')[0];
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js';
		head.appendChild(script);

		// AMG V_ID is padded V+++
		while (v_id.length < 9)
			v_id = '+'+v_id;
		v_id = 'V'+v_id;

		$.ajax({
			type: 'get',
			url: '/pinpoint-proxy.php?v_id='+v_id,
			dataType: 'xml',
			success: function(xml) {
				$(xml).find('PublishedId').each(function() {
					if (window.ivaPlayerLoaded == true)
						return;
					window.ivaPlayerLoaded = true;
					preLoadIvaPlayerDiv($(this).text());
				});
			}
		});
	});
	// End Review Trailers IVA
	// --------8<--------

});


/*
 * Coming Soon widget functions
 */
// http://stackoverflow.com/questions/1689679/javascript-how-to-sort-an-array-of-records-by-values-in-one-of-the-fields
function cmp(x, y) { return x > y ? 1 : x < y ? -1 : 0; }
function pad(n)    { return n<10 ? '0'+n : n; }

function enstar(e) {
    fc = fc || filmcritic();
    // fc.obsoleteFn(arguments.callee);
    fc.starratings.enstar(e);
}

function preLoadIvaPlayerDiv(publishedId) {

	var large = true;

	jQuery(function ($) {
		$('p.error-msg').replaceWith(
			'<div class="inner">'
				//+'<h3 class="widget-header">Watch Trailer<!-- and Related Video --><'+'/h3>'
				+'<div class="widget-content"><div class="widget-content-inner">'
					+'<div class="widget-video-player">'
						+'<div id="IvaContent"><'+'/div>'
					+'<'+'/div>'
					+'<div style="text-align: right"><a href="http://www.VideoDetective.com" title="Visit Video Detective" target="_blank">Trailers from Video Detective<'+'/a><'+'/div>'
				+'<'+'/div><'+'/div>'
			+'<'+'/div>'
		);

		// Player goes before the Movie Guide related content
		// Styling similar to Brightcove
		if (!$('#IvaContent').length && !$("link[rel='lucy-state'][href='Coming Soon']").length && !$("link[rel='lucy-state'][title='Coming Soon']").length) {
			large = false;
			$('div#beta-inner').prepend(
				'<div class="widget-video widget">'
					+'<div class="inner">'
						+'<h3 class="widget-header">Watch Trailer<'+'/h3>'
						+'<div class="widget-content"><div class="widget-content-inner">'
							+'<div class="widget-video-player">'
								+'<div id="IvaContent"><'+'/div>'
							+'<'+'/div>'
							+'<div style="text-align: right"><a href="http://www.VideoDetective.com" title="Visit Video Detective" target="_blank">Trailers from Video Detective<'+'/a><'+'/div>'
						+'<'+'/div><'+'/div>'
					+'<'+'/div>'
				+'<'+'/div>'
			);
		}

//		// Advertising requirement
//		$('#footer-ad-inner).prepend('<div id="IvaCompanion" style="padding: 15px"><'+'/div>');

		// Load the DIV
		loadIvaPlayerDiv(publishedId, large);

	}); // jQuery function scope
}

function loadIvaPlayerDiv(publishedId, large) {

	if (window.console) console.log('Displaying [', publishedId, ']');
	if (!window.swfobject) {
		setTimeout("loadIvaPlayerDiv("+publishedId+","+large+")", 500);
		if (window.console) console.log("swfobject not ready: reloading in 500 ms");
		return false;
	}

	var hd = true;
	var playerId = hd ? 216 : 202;

	try {
		swfobject.embedSWF(
			'http://www.videodetective.net/flash/players/?customerid=100275&playerid='+playerId+'&publishedid='+publishedId+'&playlistid=0&pversion=4&videokbrate=450&sub=',
			'IvaContent',
			(large?'530':'348'), (large?'409':'309'),
			'9.0.0',
			'expressInstall.swf',
			{},{
				//skin: 'Stylish_Slim',
				//autostart: 'false',
				menu: 'false',
				allowScriptAccess: 'always',
				allowNetworking: 'all',
				allowfullscreen: 'true',
				'wmode':'transparent'
			},{
				id: 'IvaPlayer',
				name: 'IvaPlayer'
			}
		);
	}
	catch(e) {
		setTimeout("loadPlayerDiv("+publishedId+","+large+")",1000);
		if (window.console) console.log("Exception ", e, " caught: reloading in 1000 ms");
	}
	return false;
}

