
var lang_text = new Array();
var params = new Array();
var selected_video_id = null;

function getVideoList(params) {
	switch (params['order_by']){
						case 'rating':
							params['time'] = 'all_time';
							params['order'] = 'rating';
							break;
						case 'this_week':
							params['time'] = 'all_time';
							params['order'] = 'published';
							break;
						case 'rating2':
							params['time'] = 'all_time';
							params['order'] = 'viewCount';
							break;
						case 'this_week2':
							params['time'] = 'this_week';
							params['order'] = 'rating';
							break;
						case 'this_month':
							params['time'] = 'this_month';
							params['order'] = 'rating';
							break;
					}


	$.ajax({
		   type: "POST",
		   url: "ajax/video_replays_call.php",
		   data: "product_id="+params['product_id']+"&order_by="+params['order']+"&start_index_video="+params['start_index_video']+"&max_res="+params['max_res']+"&time="+params['time'],
		   success:function(val){
				var videos = json_decode(val);
				$('#vidList').empty();
				// load default video for show
				$('#rateIt').unbind('click');
				$('#rateIt').click(function (){
					window.open('http://www.youtube.com/watch?v='+videos[0]['id']);
				});

				$('#author').text(videos[0]['author']);
				$('#views').text(videos[0]['views']);
				//$('#current_date').text(videos[0]['date'].substr(0,10));
				$('#total_results').text(videos['totalResults'] + ' videos');
				delete(videos['totalResults']);
				
				var playerurl = videos[0]['playerurl']+'&hl=es&fs=1&rel=0';
				$('#replayVideoContainer').html('<embed src="'+playerurl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="394" height="333" wmode="transparent"></embed>');
				
				printComments(videos[0]['comments_url'],videos[0]['comments_count']);
				
				// set page
				$('#start_index_video').val(params['start_index_video']);
				
				// video category select
				var select = '<select id="category">';
				var cats = new Array();
				var cat_text = new Array();
				cats[1]	= 'rating';
				cats[2]	= 'this_week';
				cats[3]	= 'rating2';
				cats[4]	= 'this_week2';
				cats[5]	= 'this_month';
				cat_text[1] = lang_text['top_rated'];
				cat_text[2] = lang_text['latest_videos'];
				cat_text[3] = lang_text['most_viewed'];
				cat_text[4] = lang_text['weekly_ranking'];
				cat_text[5] = lang_text['monthly_ranking'];
				
				for (var x= 1; x<=5; x++) {
					if (cats[x] == params['order_by']){
						select += '<option selected=selected value="'+cats[x]+'">'+cat_text[x].toUpperCase()+'</option>';
						var cat_title = cat_text[x].toUpperCase();
					} else {
						select += '<option value="'+cats[x]+'">'+cat_text[x].toUpperCase()+'</option>';
					}
				}
				select += '</select>';
				$('#category').remove();
				//$('#mostViewed').empty();
				//$('#mostViewed').append(select);
				$('#total_results').before(select);
				$('#h2title').empty();
				$('#h2title').text(cat_title);
				$('#youtubePager h2').text(cat_title);
				
				if ((lang == 'es' || lang == 'it' || lang == 'de' || lang == 'fr') && (params['order_by'] == 'this_week2' || params['order_by'] == 'this_month')){
					$('#h2title').attr({style:'font-size:13px;'});
					$('#youtubePager h2').attr({style:'font-size:13px;'});
				} else {
					$('#h2title').removeAttr('style');
					$('#youtubePager h2').removeAttr('style');
				}

				star_style = $('#replayHeader p img').css('left');
				
				if (lang == 'jp') {
					$('#replayHeader p a strong').attr({style:'font-size:10px;'});
					$('#replayHeader p img').css('left', '0');
				} else {
					$('#replayHeader p a strong').removeAttr('style');
					if (star_style != $('#replayHeader p img').css('left')) { $('#replayHeader p img').css('left', star_style); }
				}
				
				// create video list 
				//$('#thumb_img').attr({src:videos[0]['big_thumb_url']});
				
				// Pagination
				$('#vlp_left').unbind('click');
				if (videos['prev'] == 1) {
					$('#vlp_left').css('visibility','visible');
					$('#vlp_left').click(function(){
						params['start_index_video'] = parseInt($('#start_index_video').val()) - 10;
						getVideoList(params);
					});
				} else {
					$('#vlp_left').css('visibility','hidden');
				}
				$('#vlp_right').unbind('click');
				if (videos['next'] == 1) {
					$('#vlp_right').css('visibility','visible');
					$('#vlp_right').click(function(){
						params['start_index_video'] = parseInt($('#start_index_video').val()) + 10;
						getVideoList(params);
					});
				} else {
					$('#vlp_right').css('visibility','hidden');
				}
				
				delete(videos['next']);
				delete(videos['prev']);

				var first_video_id = null;
				
				for (var i in videos) {
					
					//rating & pos
					var pos = parseInt(videos[i]['pos']);
					var stars = '';
					for (var y= 1; y<=5; y++){
						if ( y <= parseInt(videos[i]['rating']) ){
							stars += '<img src="http://media01.gameloft.com/web_mkt/minisites/lets-golf-2/images/star_on.jpg" width="10" height="8" />';
						}else{
							stars += '<img src="http://media01.gameloft.com/web_mkt/minisites/lets-golf-2/images/star_off.jpg" width="10" height="8" />';
						}
					}


					// Dates for countries
					var vdate = videos[i]['date'].substr(0,10);
					if (lang == 'fr') {
						var vdate = videos[i]['date'].substr(0,10);
						date_pieces = vdate.split("-");
						vdate = date_pieces[2] + '-' + date_pieces[1] + '-' + date_pieces[0];
					}
					
					// caption switch
					var caption = 'RATING<br>';
					switch (params['order_by']){
						case 'rating':
						case 'this_week2':
						case 'this_month':
							caption = lang_text['rating'].toUpperCase()+'<br/>';
							caption += stars;
							break;
						case 'this_week':
							caption = '<span style="line-height:2.4em">' + vdate + '</span>';
							break;
						case 'rating2':
							caption = lang_text['views'].toUpperCase()+'<br/>'+videos[i]['views'];
							break;
					}
					
					// create info array for selection
					var info_id = videos[i]['id'];
					var info_author = videos[i]['author'];
					var info_views = videos[i]['views'];
					var info_playerurl = videos[i]['playerurl'];
					var info_date = videos[i]['date'];
					var comment_url = videos[i]['comments_url'];
					var comment_count = videos[i]['comments_count'];

					if (first_video_id == null) first_video_id = info_id;
					
					// build item
					$('#vidList').append('<li id="' + info_id + '"><label>'
					+pos
					+'</label><img width="70 " height="70" onClick="javascript: selectVideo(\''+info_id+'\',\''+info_author+'\',\''+info_views+'\',\''+info_playerurl+'\',\''+info_date+'\',\''+comment_url+'\',\''+comment_count+'\')" src="'
					+videos[i]['big_thumb_url']
					+'" /><div><span class="">'
					+caption
					+'</span></div></li>');

				}
				$('#category').change(function(){
					params['order_by'] = $('#category').val();
					getVideoList(params);
				});
				
				highlightSelectedVideo(first_video_id);
				
				$('#vidList li').hover(
					function(){
						if ($(this).attr('id') != selected_video_id){
							$(this).css({'border':'2px solid #98AF15'});
							$(this).children('label').css({'background-position':'top right','color':'#fff'});
						}
					},
					function(){
						if ($(this).attr('id') != selected_video_id){
							$(this).css({'border':'2px solid #98AF15'});
							$(this).children('label').css({'background-position':'top left','color':'#000'});
						}
					}
				);
				
		   }});
}

function highlightSelectedVideo(video_id){
	$('#vidList #'+video_id).css({'border':'2px solid #98AF15'});
	$('#vidList #'+video_id).children('label').css({'background-position':'top right','color':'#fff'});
	
	if (selected_video_id != null) {
		$('#vidList #'+selected_video_id).css({'border':'2px solid #98AF15'});
		$('#vidList #'+selected_video_id).children('label').css({'background-position':'top left','color':'#000'});
	}
	
	selected_video_id = video_id;
}

function selectVideo(info_id, info_author,info_views,info_playerurl,info_date,comment_url,comment_count) {
	highlightSelectedVideo(info_id);
	
	$('#rateIt').unbind('click');
	$('#rateIt').click(function (){
		window.open('http://www.youtube.com/watch?v='+info_id);
	});

	$('#author').text(info_author);
	$('#views').text(info_views);
	//$('#current_date').text(info_date.substr(0,10));
	var playerurl = info_playerurl+'&hl=es&fs=1&rel=0';
	$('#replayVideoContainer').html('<embed src="'+playerurl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="394" height="333" wmode="transparent"></embed>');
	
	printComments(comment_url,comment_count);
}

function printComments(comment_url,comment_count) {
	$.ajax({
		   type: "POST",
		   url: "ajax/ajax_get_comment.php",
		   data: "comment_url="+comment_url+"&comment_count="+comment_count,
		   success:function(val){
				var comments = json_decode(val);
				$('#comments').empty();
				var commentsList = '';
				for (var i in comments) {
						commentsList += 'User: <b>'+comments[i]['author']
						+'</b><br/>'+comments[i]['msg']
						+'<br/><br/>';
				}
				
				$('#comments').append('<p>' + commentsList + '</p>');				
		   }});
}

   function getLangText() {
	/*   
   var $_GET = getQueryParams(document.location.search);
   if (typeof($_GET['lang']) == 'undefined' || $_GET['lang'] == 'global') {
		$_GET['lang'] = ( typeof(language) != 'undefined' ? language : 'us' );
   }
   */
   
    var  selectedLang = (lang == 'uk' || lang == 'us' || lang == 'world') ? 'en':lang;
	
	$.ajax({
		   type: "GET",
		   url: "includes/getTexts.php",
		   data: "lang="+selectedLang,
		   success:function(val){
				var arr = new Array();
				lang_text = json_decode(val);
				getVideoList(params);
    }});
	
	}
	
	function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {};
    var tokens;

		while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
			params[decodeURIComponent(tokens[1])]
				= decodeURIComponent(tokens[2]);
		}
    return params;
	}
	
function json_decode (str_json) {
    // Decodes the JSON representation into a PHP value  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/json_decode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + improved by: T.J. Leahy
    // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *     returns 1: ['e', {pluribus: 'unum'}]
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */

    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        return json.parse(str_json);
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if ((/^[\],:{}\s]*$/).
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        j = eval('(' + text + ')');

        return j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.
    throw new SyntaxError('json_decode');
}

function getVideoListFromCategory(category){
	params['product_id'] = '913';
	params['order_by'] = category;
	params['max_res'] = '9';
	params['start_index_video'] = "1";
	getVideoList(params);
}

	$(document).ready(function(){
	// HTML VIDS
		params['product_id'] = '913';
		params['order_by'] = $('#order_by').val();
		params['max_res'] = '9';
		params['start_index_video'] = $('#start_index_video').val();
		getLangText();

		$('#view_most_viewed').click(function(){
			getVideoListFromCategory('rating2');
		});

		$('#view_latest_videos').click(function(){
			getVideoListFromCategory('this_week');
		});
		
		$('#view_monthly_ranking').click(function(){
			getVideoListFromCategory('this_month');
		});
		
		$('#view_weekly_ranking').click(function(){
			getVideoListFromCategory('this_week2');
		});
		
		$('#view_top_rated').click(function(){
			getVideoListFromCategory('rating');
		});

		//Already do this			
		//$('.youtubeSelects h3').toggle(
		//	function(){
		//		$('.youtubeSelects div').slideUp(300);
		//		$(this).parent('div.youtubeSelects').children('div').slideDown(300);
		//		$(this).children('img').attr('src','images/videoreplays/arrow_up.jpg');
		//	},function(){
		//		$('.youtubeSelects div').slideUp(300);
		//		$('.youtubeSelects h3 img').attr('src','images/videoreplays/arrow.jpg');
		//	}
		//);
   });

