
var lang_text = new Array();
var params = new Array();

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);
			$('#photos').empty();
			
			// load default video for show
			$('#current_user').text(videos[0]['author']);
			$('#current_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';
			
			$('#youtube').html('<embed src="'+playerurl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="460" height="385"></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>';
			
			$('#mostViewed').empty();
			$('#mostViewed').append(select);
			$('.video_type_title').empty();
			$('.video_type_title').text(cat_title);
			
			// 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']);
			
			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 height="8" width="10" src="images/videoreplays/star_on.jpg"/>';
					}
					else
					{
						stars += '<img height="8" width="10" src="images/videoreplays/star_off.jpg"/>';
					}
				}
				
				// Dates for countries
				var vdate = videos[i]['date'].substr(0,10);
				if ( $('#lang').val() == '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_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'];

				// build item
				$('#photos').append('<li><div class="position">'
				+pos
				+'</div><div class="vl_thumb" onClick="javascript: selectVideo(\''+info_author+'\',\''+info_views+'\',\''+info_playerurl+'\',\''+info_date+'\',\''+comment_url+'\',\''+comment_count+'\')"><img src="'
				+videos[i]['big_thumb_url']
				+'" /></div><div class="vl_caption">'
				+caption
				+'</div></li>');
				
			}
			$('#category').change(function(){
				params['order_by'] = $('#category').val();
				getVideoList(params);
			});
	}});
}


function selectVideo( info_author,info_views,info_playerurl,info_date,comment_url,comment_count) 
{
	$('#current_user').text(info_author);
	$('#current_views').text(info_views);
	$('#current_date').text(info_date.substr(0,10));
	var playerurl = info_playerurl+'&hl=es&fs=1&rel=0';
	$('#youtube').html('<embed src="'+playerurl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="460" height="385"></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();
				for (var i in comments) {
					$('#comments').append(
						'User: <b>'+comments[i]['author']
						+'</b><br/>'+comments[i]['msg']
						+'<br/><br/>'
					);
				}
		   }});
}

function getLangText() 
{
   var $_GET = getQueryParams(document.location.search);
   if (typeof($_GET['lang']) == 'undefined' || $_GET['lang'] == 'global') {
		$_GET['lang'] = ( typeof(language) != 'undefined' ? language : 'us' );
}
   
	$.ajax({
		   type: "POST",
		   url: "iphone/includes/getTexts.php",
		   data: "lang="+$_GET['lang'],
		   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');
}

$(document).ready(function()
{
	// HTML VIDS
	params['product_id'] = '883';
	params['order_by'] = $('#order_by').val();
	params['max_res'] = '11';
	params['start_index_video'] = $('#start_index_video').val();
	getLangText();

	$('.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');
		}
	);
});

