var $wj = jQuery.noConflict();

$wj(function(){ 

//first hide the navigation links (next /previous)
$wj(".nextprevNavBar").hide();

//get the floabl drawer element used to display messages to user
var drawer=$wj("#drawer");

//var err = typeof php_error != 'undefined';
//get the list of rooms from the html javascript the php saved
if(php_rooms != 'undefined') var rooms = eval(php_rooms);

//init the room selected global
var selected_room_id = -1;
var last_room = -1;
var lasterror = false;

//get and set the hight of the affiliate rooms table based on dynamic content
function sethigh(){
	var boxh = parseInt($wj(".table1:last").height());
	var wiztblh = parseInt($wj(".scrollable:eq(0)").height());
	if( boxh>400) {
		$wj("#mainu").animate({height: [( wiztblh+(boxh-400) ), 'linear']}, '1000', 'linear');
		$wj(".scrollable:eq(0)").height( wiztblh+(boxh-400) );
	}
}

sethigh();

function resethigh() {
	
}


/** 
	handles click on the affilate room table 
	it will save a gloabl var with the affilate room
*/
$wj(".box9-bottom table tbody tr").each(function(){   
	//setup tooltip
		var el = $wj(this);
		el.tooltip({      
			position : 'top center',
			offset: [50, 350],
			effect: 'slide',
			relative: true,
			tip : '#tt_'+el.attr('id')
		}).dynamic({ bottom: { direction: 'down', bounce: true } });
		
	}).click(function(){
	
		var roomfound = false;
		var roomid = jQuery(this).find('.poker a').attr('rel');
	
	jQuery.each(rooms, function(key, value) { 
		if(roomid == value.id){
			selected_room_id = key;
			roomfound=true;
		}
	});
	
	if(!roomfound) {
		selected_room_id=-1;
	
	} else {
		
		if(last_room != selected_room_id) {
			
			//showMsg('Loading Poker Room...');
			
			$wj(this).parent().children(last_room).removeClass('active');
		
			//get the next page element and load data via ajax
			//var it = horizontal.eq(1).find('.items');
			
			//if we this is not the first selectoion
			//if(last_room != -1 && !lasterror) it.children().remove();
			
			last_room = selected_room_id;
			$wj("#mainu").scrollable().next();
			//resethigh();
			/*
			it.append().load(icl_home+"/get-free-license/single",{roomid: rooms[selected_room_id]['id']}, function(response, status, xhr){
				
				if(status != "error"){
					//reset lasterror
					lasterror = false;
					// Set scrollabe after load content
					$wj(".scrollable").scrollable();		
					// Added this line to recalculate the size
					$wj(".scrollable").data("scrollable").addItem();
					$wj(".scrollable").data("scrollable").begin(0);  
					$wj("#mainu").scrollable().seekTo(1);
					it.parent().find(".nextprevNavBar").show();
					var size = horizontal.eq($wj("#mainu").scrollable().getIndex()).data("scrollable").getSize();
					if(size > 1) $wj(".navCount").text(size);
				} 
				else lasterror = true; 
			});*/
		}
		//set the selected tr to active
		$wj(this).addClass('active');
	}
});

/** main vertical scroll **/
$wj("#mainu").scrollable({
	vertical: true,
	size: 3,
	keyboard: 'static',
	clickable: false,
	absolute: true, 
	
	onBeforeSeek: function(event, i) {
		//hide any errors
		$wj(".error").hide();
		
		//check for php processing errors
		var err = typeof php_error != 'undefined';
		if( err ) return false;
		
		//replace the rooms specific variables in the html pages
		if(selected_room_id != -1) {
			jQuery.each(rooms[selected_room_id], function(key, value) {
				if(key !="download_link") {
					$wj(".room_"+key).text(rooms[selected_room_id][key]);
				} else {
					$wj("a[href='#'].room_"+key).attr('href', rooms[selected_room_id][key]);
				}
				
			});
			
		} else {
			return false;
		}
		horizontal.eq(i).data("scrollable").begin(0);
		$wj(".navCurCount").text('1');
	},
	
	/** assign left/right keys to the actively viewed scrollable **/
	onSeek: function(event, i) {
		//clear and message
		drawer.slideUp();
		//scroll horizontal
		horizontal.eq(i).data("scrollable").focus();
	}
	
/** --> main navigator (thumbnail images) <-- **/
}).navigator({
		navi: '#main_navi' 
});

	
	/*tell the user to select a room */
	$wj('#main_navi').click(function(i) {
		if(selected_room_id == -1) { 
			showMsg('Please Select a Poker Room From the Table First');
			setTimeout(function() { drawer.slideUp(600); }, 3000);
		}
	});

	var horizontal = $wj(".scrollable").scrollable({ circular: false, prev: ".prevPage",next: ".nextPage"}).navigator(".navi");
	    
	/** when page loads setup keyboard focus on the first horizontal scrollable **/
    horizontal.eq(0).data("scrollable").focus();
	
 
	$wj(".nextPage").click(function() {    
		var cnt = horizontal.eq($wj("#mainu").scrollable().getIndex()).data("scrollable").getIndex() + 1;
		if(cnt > 0) $wj(".navCurCount").text(cnt);
		
	});

	$wj(".prevPage").click(function() {    
		var cnt = $wj(".navCurCount").html() -1;
		if(cnt > 0) $wj(".navCurCount").text(cnt);
	});

 
//setup red border on errors
$wj("#gfl-details").bind("onFail", function(e, errors)  {

	// we are only doing stuff when the form is submitted
	if (e.originalEvent.type == 'submit') {

		// loop through Error objects and add the border color
		$wj.each(errors, function()  {
			var input = this.input;
			input.css({borderColor: 'red'}).focus(function()  {
				input.css({borderColor: '#444'});
			});
		});
		showMsg('You did not enter all required information, please correct the errors higlighted in red');
	}
});


$wj("#gfl-details").validator().submit(function(e){
	
	var gflForm = $wj(this);
	//var gflFields=gflForm.serialize();
		
	if(!e.isDefaultPrevented()) {
		_gaq.push(['_trackEvent', 'GFL', 'Submit']);
		$wj.ajax({
			type: "post",
			url: icl_home + "get-free-license/init",
			dataType: 'json',
			data: gflForm.serialize()+"&service=cnewgfl&aff_id="+rooms[selected_room_id]['id'],
			
			 beforeSend: function() {
				showMsg('Processing Your Request, Please Wait...');
			},
				 
			success: function (data, textStatus) {
				if(data.error == true){
					_gaq.push(['_trackEvent', 'GFL', 'Response','Fail']);
					showMsg('Request Failed: ' +data.Detail);
					gflForm.data("validator").invalidate("activation-code:"+data.Detail);
					gflForm.append('<input type="hidden" name="result" value="FAIL" />');
					gflForm.append('<input type="hidden" name="result_message" value="'+data.Detail+'" />');
					
				} else {
					_gaq.push(['_trackEvent', 'GFL', 'Response','Success']);
					drawer.slideUp();
					gflForm.append('<input type="hidden" name="result" value="OK" />');
					gflForm.append('<input type="hidden" name="invoice" value="'+data.id+'" />');
					gflForm.append('<input type="hidden" name="room_name" value="'+rooms[selected_room_id]['name']+'" />');
					gflForm.unbind('submit');
					gflForm.submit();
				}
			},
			
			error: function (data) {
				_gaq.push(['_trackEvent', 'GFL', 'Response','Fail']);
				//alert(data.error);
				showMsg('Request Submission Failed, ' +data.Detail+", Please Try Again Later...");
			}
			
		});
		
		e.preventDefault();
	}	
});

	drawer.hide();
	//show error message as a top drawer
	function showMsg(msg) {
		var drawererr=false;
		timeout=5000;
		
		//alert('ff');
		drawer.text(msg);
		
		border = (drawererr) ? "#FF0F0F" : "#666";
		
		drawer.slideDown(function()  {
			drawer.css({"backgroundColor": "#eeb350", "borderColor": border});
			//setTimeout(function() { drawer.slideUp(); }, timeout);
		});
	};

	$wj(':input').focus(function(){
		drawer.slideUp(500);
	});
	
});