// JavaScript Document
$(document).ready(function() {
													 
	$(":checkbox").click(function(){
        if($.browser.msie){
            $(this).fire("change");
        }
    });
													 
	$('a.add_bookie_cancel').click(function(e){
		e.preventDefault();
		$('.bookie_holder').fadeOut('fast');
	});
	
	$('a.add_bookie').live("click", function(e){
		e.preventDefault();
		var cls = $(this).attr('class');
		cls = cls.split(' ');
		var parts = cls[1].split('_');
		popup_bookie_edit(parts[0], parts[1]);
	});
	
	$('a.edit_bookie_url').live("click", function(e){
		e.preventDefault();
		var cls = $(this).attr('class');
		cls = cls.split(' ');
		var parts = cls[1].split('_');
		var url = $('td.url_' + parts[0] + '_' + parts[1]).text();
		popup_bookie_edit(parts[0], parts[1], url);
	});
	
	
	$('.bookie_rem').live("click", function(e) {
		e.preventDefault();
		var cls = $(this).attr('class');
		cls = cls.split(' ');
		var parts = cls[1].split('_');
		var bookie_id = parts[1];
		var provider_id = parts[0];
		removeAffiliateBookie(bookie_id, provider_id);
		$(this).parents('tr').remove();
		var li = build_bookie_li(bookie_id, provider_id);
		
		$('.available_bookies_list').append(li);
		$('.available_bookies_list li.no_bookie').remove();
	

		reorder_bookies('.draggableTable', false);
	});
	
	$('.set_vis').live("click", function(e) {
		e.preventDefault();
		var cls = $(this).attr('class');
		cls = cls.split(' ');
		var bookie_id = cls[1].replace('vis_bookie_', '');
		var status = cls[2].replace('set_vis_', '');
		updateAffiliateBookieStatus(bookie_id, status, this);
		
	});
	
	$('a.add_bookie_submit').click(function(e) {
		e.preventDefault();
		submitAddBookie();
	});
	
	$('.aff_url_input').bind('keyup', function(e){
		if(e.keyCode == 13) { // enter = submit
			submitAddBookie();
		}
	});

});


function submitAddBookie() {
	var aff_url = $('.aff_url_input').val();
	if(!is_valid_url(aff_url)) {
		alert("The URL: " + aff_url + " is not valid.\nUntil you provide a valid URL, our links will be used 100% for this bookie!");
	}
	if(aff_url == 'http://' || aff_url == 'https://') {
		aff_url = '';
	}
	add_bookie_ajax(selected_affiliate_bookie, aff_url, selected_affiliate_provider);
	$('.bookie_holder').hide();
}


function is_valid_url(url) {
	regexp = /^https?:((\/\/))+[\w\d:#@%\/;\$\(\)~_\?\+=\\\.&-]+\.[a-z]{2,4}\/?((\?|#|\/)+[\w\d:#@%\/;\$\(\)~_\?\+=\\\.&-]+)?$/i;
	if (url.match(regexp) == null) {
			return false;
	}
	return true;
}

function build_bookie_row(bookie_id, provider_id, aff_url, status) {
	var tr = '<tr class="odd tr_' + provider_id + '_' + bookie_id + '"><td class="draggable" style="cursor: move;"><span>&nbsp;</span><input type="hidden" class="sorting book_' + bookie_id + '" name="book_' + bookie_id + '" value="' + next_bookie_sorting + '" /></td><td class="b_logo"><a title="" href="#" class="sel_bookie_logo ' + provider_id + '_' + bookie_id + '"><img height="20" width="80" alt="" src="http://images.betting101.co.uk/sp/80/' + provider_id + '.gif" /></a></td><td class="aff_url"><div>' + aff_url + '</div></td><td class="b_visible"><a class="set_vis vis_bookie_' + bookie_id + ' set_vis_1" href="#"><span>1</span></a></td><td class="b_edit"><a href="#" class="edit_bookie_url ' + provider_id + '_' + bookie_id + '"><span>Edit URL</span></a></td><td class="b_remove"><a class="bookie_rem ' + provider_id + '_' + bookie_id + '" href="#"><span>x</span></a></td></tr>';
	next_bookie_sorting++;
	return tr;
}

function build_bookie_li(bookie_id, provider_id) {
	var li = '<li><a title="" href="#" class="add_bookie ' + provider_id + '_' + bookie_id + '"><img height="20" width="80" alt="" src="http://images.betting101.co.uk/sp/80/' + provider_id + '.gif"></a></li>';
	return li;
}


/***** jquery draggable: based on the solution from http://www.lukedingle.com/javascript/sortable-table-rows-with-jquery-draggable-rows/ ******/
function dragableInit(table_selector, do_reorder) {
		/***** dragable tr *******/
	//Capture the mouse x and y positions (only Y is needed for this task but there's no harm in getting
	// both axis.
	// Declare global variables so they can be accessed anywhere.
	// The lastX and lastY variables will be used to keep track of which direction the mouse is heading
	// when moving the TR elements
	var mouseX, mouseY, lastX, lastY = 0;
	// This function captures the x and y positions anytime the mouse moves in the document.
	$().mousemove(function(e) { mouseX = e.pageX; mouseY = e.pageY; });
	
	//IE Doesn't stop selecting text when mousedown returns false we need to check
	// That onselectstart exists and return false if it does -- we won't check if the browser is IE
	// As thy may very well change this at some point
	var need_select_workaround = typeof $(document).attr('onselectstart') != 'undefined';
	// The first order of business is to bind a function to the mousedown event
	// on all TR elements inside the tbody. I am using the jQuery live() function because my content is loaded through
	// ajax. simply use mousedown() if you do not need to load this on dynamic functions
		$(table_selector + ' tbody tr td.draggable').live('mousedown', function (e) {
			// Store the current location Y axis position of the mouse at the time the
			// mouse button was pushed down. This will determine which direction to move the table row
			lastY = mouseY;
			// store $(this) tr element in a variable to allow faster access in the functions soon to be declared
			var tr = $(this).parent();
			// This is just for flashiness. It fades the TR element out to an opacity of 0.2 while it is being moved.
			tr.fadeTo('fast', 0.2);
			// jQuery has a fantastic function called mouseenter() which fires when the mouse enters
			// This code fires a function each time the mouse enters over any TR inside the tbody -- except $(this) one
			$('tr', tr.parent() ).not(tr).mouseenter(function(){
				// Check mouse coordinates to see whether to pop this before or after
				// If mouseY has decreased, we are moving UP the page and insert tr before $(this) tr where
				// $(this) is the tr that is being hovered over. If mouseY has decreased, we insert after
				if (mouseY > lastY) {
						$(this).after(tr);
				} else {
						$(this).before(tr);
				}
				// Store the current location of the mouse for next time a mouseenter event triggers
				lastY = mouseY;
			});
			// Now, bind a function that runs on the very next mouseup event that occurs on the page
			// This checks for a mouse up *anywhere*, not just on table rows so that the function runs even
			// if the mouse is dragged outside of the table.
			$('body').mouseup(function () {
				 //Fade the TR element back to full opacity
				 tr.fadeTo('fast', 1);
				 // Remove the mouseenter events from the tbody so that the TR element stops being moved
				 $('tr', tr.parent()).unbind('mouseenter');
				 // Remove this mouseup function until next time
				 $('body').unbind('mouseup');
			// Make text selectable for IE again with
			// The workaround for IE based browsers
			if (need_select_workaround)
			$(document).unbind('selectstart');
			if(do_reorder == 'bookies') {
				 reorder_bookies(table_selector); // This function just renumbers the position and adjusts the zebra striping, not required at all
			}
			else if(do_reorder == 'markets') {
				reorder_markets(table_selector); //
			}
			else if(do_reorder == 'leagues') {
				reorder_leagues(table_selector); //
			}
		});
			// This part if important. Preventing the default action and returning false will
			// Stop any text in the table from being highlighted (this can cause problems when dragging elements)
			e.preventDefault();
		// The workaround for IE based browers
		if (need_select_workaround)
			$(document).bind('selectstart', function () { return false; });
			return false;
		});
	}
		
	function reorder_markets (table_selector) {
		var position = 1;
		box_market_str = '';
		$(table_selector + ' tbody tr').each(function () {
			// Change value of the hidden field inside the first TD element inside this TR
			var h = $('td.rem_market', $(this));
			var m_id = h.attr('class').replace('rem_market rem_m_', '');
			if(position > 1) {
				box_market_str += m_id + '.';
			}
			else {
				box_market_str = '.' + m_id + '.';
			}
			position += 1;
		});		
	}
	
	function reorder_leagues (table_selector) {
		var position = 1;
		box_league_str = '';

		$(table_selector + ' tr').each(function () {
			// Change value of the hidden field inside the first TD element inside this TR
			var h = $('td:last', $(this));
			var l_id = h.attr('class').replace('rem_league rem_l_', '');
			if(position > 1) {
				box_league_str += l_id + '.';
			}
			else {
				box_league_str = '.' + l_id + '.';
			}
			position += 1;
		});		
	}
	
	function reorder_bookies (table_selector, ajax_reorder) {
		var position = 1;
		var bookies_str = '';
		$(table_selector + ' tbody tr').each(function () {
			// Change value of the hidden field inside the first TD element inside this TR
			var h = $('td:first .sorting', $(this));
			h.attr('value', position);
			if(position > 1) {
				bookies_str += '-';
			}
			bookies_str += h.attr('class').replace('sorting book_', '');
			//Now remove current row class and add the correct one
			$(this).removeClass('odd even').addClass( position % 2 ? 'odd' : 'even');
			position += 1;
			
			
		});
		if(ajax_reorder == null || ajax_reorder == true) {
			ajaxBookiesReorder(bookies_str);
		}
		
	}
	
	function popup_bookie_edit(provider_id, bookie_id, url) {
		var img = $('.popup_bookie_logo');
		var src = img.attr('src');
		src = src.replace(/[\d]+\.gif$/, provider_id + '.gif');
		img.attr('src', src);
		if(url == null || url == '') {
			url = 'http://';
		}
		selected_affiliate_bookie = bookie_id;
		selected_affiliate_provider = provider_id;
		$('.aff_url_input').val(url);
		$('.bookie_holder').fadeIn('fast');
	}
	
	
	function add_bookie_ajax(bookie_id, aff_url, provider_id) {
		$.ajax({
		 type: "POST",
		 url: base_url + "my-bookies/",
		 data: "action=add_affiliate_bookie&bookie_id=" + bookie_id + "&aff_url=" + escape(aff_url),
		 //async: false,
		 success: function(msg){
			 if(msg == 'OK') {
				 var tr = build_bookie_row(bookie_id, provider_id, aff_url, 1);
				 $('table.aff_table tbody tr.no_bookies').remove();
				 
				 if($('table.aff_table tbody tr').length == 0) {
					 $('table.aff_table tbody').append(tr);
				 }
				 else {
					 var bookies_tr = $('table.aff_table tbody tr.tr_' + provider_id + '_' + bookie_id);
					 if(bookies_tr.length == 1) {
						bookies_tr.replaceWith(tr); 
					 }
					 else {
				 		$('table.aff_table tbody').append(tr);
					 }
				 }

					reorder_bookies('.draggableTable', false);
					//dragableInit('.draggableTable');
					
				 $('.available_bookies_list a.add_bookie.' + provider_id + '_' + bookie_id).parent().remove();
				 $('.bookie_holder').fadeOut('fast');
			 }
			 else {
				alert( "There was a problem adding the bookie! Please try again later");
			 }
		 }
	 });
	}
	
	function ajaxBookiesReorder(bookies_str) {
		$.ajax({
		 type: "POST",
		 url: base_url + "my-bookies/",
		 data: "action=bookies_reorder&bookies_str=" + bookies_str,
		 async: false,
		 success: function(msg){
			 
		 }
	 });
	}
	
	function updateAffiliateBookieStatus(bookie_id, status, sel) {
		new_status = status == 1 ? 0 : 1;
		$.ajax({
		 type: "POST",
		 url: base_url + "my-bookies/",
		 data: "action=update_bookie_status&bookie_id=" + bookie_id + "&status=" + new_status,
		 async: false,
		 success: function(msg){
			 if(msg == 'OK') {
				$(sel).removeClass('set_vis_' + status).addClass('set_vis_' + new_status);
			 }
			 else {
				alert("There was an error updating the bookie!\nPlease try again"); 
			 }
		 }
	 });
	}
	
	function removeAffiliateBookie(bookie_id, provider_id) {
		$.ajax({
		 type: "POST",
		 url: base_url + "my-bookies/",
		 data: "action=remove_affiliate_bookie&bookie_id=" + bookie_id + "&provider_id=" + provider_id,
		 async: false,
		 success: function(msg){

		 }
	 });
	}
	
 
$.fn.extend({
    fire: function(evttype){ 
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents'); 
            evt.initEvent(evttype, false, false); 
            el.dispatchEvent(evt); 
        } else if (document.createEventObject) { 
            el.fireEvent('on' + evttype); 
        }
        return this;
    }
});

$.fn.af_center = function () {
    this.css("position","absolute");
		//alert($(window).height() + ' - ' + $(window).width() + ' - ' + $(window).scrollLeft());
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
