// This block allows visiting specific pages in the games section via url variables
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

code_filter = '';	
       
$(document).ready(function() { 

    // We will retrieve how far the user is from their next bonus on click now, not just by default - this is to improve performance for most users.
    $('#auto_entry_link').click(function() {
        cid = $("form[name=let_there_be_cid] input[name=cid]").val();
        $.post('get_next_bonus_dollar_amount', { cid: cid, bonus: 'instant_replay' }, function(data) {
                $('#auto_entry_link').html("<p class='instant_replay_copy'>" + data.bonus_copy + "</p>");
                // reset cid
                $("form[name=let_there_be_cid] input[name=cid]").val(data.cid);
        });
    });
 
    $('#choose_game_btn').click(function(){
        $('#game_chooser').show();
        return false 
    });

    $('#game_chooser').click(function(){
        $('#game_chooser').hide();
    });

    $('#generate_frequency_link').click(function() {
        $('#frequency_form').submit();
    });
	
	//hiding check box on notification page
	$('#sms_jackpot_alert-option-group').hide();
    
    // activate the modal overlay
    $('#modal').jqm({ ajax: '@href',
                      trigger: 'a.modal_trigger',
                      target: '#remote_content' 
    });
    
    // replace the no flash button with a text link
    var noflashCopy = $("#noflash_link input[type='submit']").val()
    $("#noflash_copy").append(noflashCopy);
    $("#noflash_copy").click(function(){
        $("#noflash_link").submit();  
    });
    $("#noflash_copy").css({cursor: "pointer",
                            textDecoration: "underline"});
    $("#noflash_link").hide();
                      
    // generate popups for global nav items               
    $("a[rel=popup]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=500px,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })
    
    $("a[rel=popup2]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=730px,height=416,scrollbars=0,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })
    
    $("a[rel=auto_entry_popup]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=642px,height=400,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })

    $("a[rel=external]").click(function(){
           popupWindow = window.open(this.href,this.title,'width=800,height=600,toolbar=yes,status=yes,location=yes,menubar=yes,directories=yes,resizable=yes,scrollbars=yes');
           popupWindow.focus()
           return false;
    })

    $("a[rel=raffle_code_info]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=630px,height=380,scrollbars=0,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })
    
    // submit user's flash version with the FAQ form
    var flash = deconcept.SWFObjectUtil.getPlayerVersion();
    $("input#flash").val(flash.major + '.' + flash.minor + '.' + flash.rev);
    
    $("#popup_close_button").click(function() {
        window.close();
    });
    
    // Un-comment for prechecked Opt-ins
	if (!$("div").hasClass("error")) {
    	$("#registration input[name=primary_opt_in]").attr("checked", "checked");
    }
    
    
    
    // Nav
    // hover highlighting
    $("#nav li, #nav li ul li").hover(
    	function() {
    		$(this).addClass("hover");
    	},
    	function() {
    		$(this).removeClass("hover");
    	}
    );
    
    
    // Lotto grid
    // Rollover drawing info
    $("#lotto_numbers .lotto_num").hover(
    	function() {
    		if ($(this).attr("has_rollover") == "1") {
    			$(this).children(".winning_numbers").hide("default");
    			$(this).children(".drawing_info").slideToggle("default");
    		}
    	},
    	function() {
    		if ($(this).attr("has_rollover") == "1") {
    			$(this).children(".drawing_info").slideToggle("default");
    			$(this).children(".winning_numbers").show("default");
    		}    		
    	}
    );
    
    // Drawing numbers inline popup
    $("#lotto_numbers .numbers_popup_trigger").click(function() {
    	drawing = $(this).attr("drawing");
    	$("#lotto_numbers .numbers_popup[drawing="+drawing+"]").slideToggle("default");
    });
    $("#lotto_numbers .numbers_popup .close_this").click(function() {
    	$(this).parent().slideToggle("default");
    });

    
    // HOVER VERSION
    $("#lotto_numbers .numbers_popup_trigger").hover(
    	function() {
    		has_rollover = $(this).attr("has_rollover");
    		if (has_rollover == 1) {
	    		drawing = $(this).attr("drawing");
	    		$("#lotto_numbers .numbers_popup[drawing="+drawing+"]").slideToggle("default");
	    	}
    	},
    	function() {
    		// do nothing on mouseout - let next function close window
    	}
    );
    $("#lotto_numbers .numbers_popup").hover(
    	function() {
    		// do nothing on hover
    	},
    	function() {
    		has_rollover = $(this).attr("has_rollover");
    		if (has_rollover == 1) {
    			$(this).slideToggle("default");
    		}
    	}
    );

	
	// Notifications Page Tooltips	
	tooltip_style = { 
    	border: "2px solid #87918b", 
    	background: "#addc95", 
    	color: "#000", 
    	padding: "10px", 
    	zIndex: "1000", 
    	textAlign: "left" 
	}
	$("#update_notifications .help").wTooltip({
		fadeIn: 600, 
		fadeOut: "slow",
		className: "tooltip",
		offsetY: -20,
	    offsetX: -450,
		style: tooltip_style
	});
	
    
    $('#code_filter').change(function(){

                cur_table = $("table.account_history[table=point_transactions]");
                cur_table.fadeIn();
                table_name = "point_transactions";
                // I know this looks wierd, but we start with "0" in this particular section because we do pagination in perl with the filter, not with mysql.
                // You'll notice that in the page change block we start with "1" - this is intended...don't change it.
                if (this.value == '') {
                    start_num = 1;
                } else {
                    start_num = 0;
                }

                items_per_page = parseInt(cur_table.attr("per_page"));
                cid = $("form[name=let_there_be_cid] input[name=cid]").val();
                
                // clear current table
                cur_table.children("tbody").html('<tr><td><img src="public/images/ajax-loader2.gif" alt="Loading..." style="margin: 20px 0 50px 8px;" /></td></tr>');
                
                // ajax time
                $.post('filter_code_entry', { cid: cid, start: start_num, per_page: items_per_page, code_filter: this.value }, function(data) {
                        // Make sure to comment out when no longer in test mode.. it asplodes IE
                        // console.debug(data);
                        if (data.code_filter != '') {
                            code_filter = data.code_filter;
                        } else {
                            code_filter = '';
                        }
                        // make button inactive if none left
                        if (data.left == 0) {
                                $("table.account_history[table="+table_name+"] span.next").addClass("inactive");
                        } else {
                                $("table.account_history[table="+table_name+"] span.next").removeClass("inactive");
                        }
                        // use start_num for previous because left counts 0
                        if (start_num == 0) {
                                $("table.account_history[table="+table_name+"] span.previous").addClass("inactive");
                        } else {
                                $("table.account_history[table="+table_name+"] span.previous").removeClass("inactive");
                        }
                        
                        // reset cid
                        $("form[name=let_there_be_cid] input[name=cid]").val(data.cid);
                        
                        // conjure up new data
                        var table_html = "";
                        for (var i in data.transactions) {
                                // definte data columns depending on which table this is
                                var table_items = new Array();
                                if (data.transactions[i].type_sym == 'SURVEY_TAKEN') {
                                        table_items = ['Polling', data.transactions[i].point_value, 'Poll', data.transactions[i].created, 'Polling'];
                                } else {
                                        table_items = [type_sym_copy[data.transactions[i].type_sym], data.transactions[i].point_value, data.transactions[i].code_class_description, data.transactions[i].created, data.transactions[i].description];
                                }
                                table_html += "<tr>\n";
                                // create tds
                                for (var z in table_items) {
                                        // prevent js from writing "undefined" when it gets a null field
                                        if (table_items[z] == null) {
                                                table_items[z] = " ";
                                        }
                    table_html += "<td>"+table_items[z]+"</td>\n";
                                }
                table_html += "</tr>\n";
                        }
                        cur_table.children("tbody").html(table_html);
                });
                
                // misc cleanup
                cur_table.attr("start", start_num);

    });


	// Account History Pagination
	$("table.account_history tfoot span.change_page").click(function() {
		// only do stuff if there are items on the next page
		
		if (!$(this).hasClass("inactive")) {		
			// definitions
			if ($(this).hasClass("next")) {
				direction = "next";
			} else {
				direction = "previous"
			}
			cur_table = $(this).closest("table");
			table_name = cur_table.attr("table");
			items_per_page = parseInt(cur_table.attr("per_page"));
			start_num = parseInt(cur_table.attr("start"));
			if (direction == "next") {
				start_num += items_per_page;
			} else {
				start_num -= items_per_page;
			}
			cid = $("form[name=let_there_be_cid] input[name=cid]").val();
			
			// clear current table
			cur_table.children("tbody").html('<tr><td><img src="public/images/ajax-loader2.gif" alt="Loading..." style="margin: 20px 0 50px 8px;" /></td></tr>');
			
			// pick a method, any method
			if (table_name == "point_transactions") {
				cur_method = "get_point_trans";
			} else if (table_name == "redemption_transactions") {
				cur_method = "get_redemption_trans"
			} else if (table_name == "auto_entry") {
				cur_method = "get_autoentry_trans"
			} else if (table_name == "iw_overlay") {
				cur_method = "get_iw_overlay_trans"
			}
			
			// alert("Passing in...\n\ncid: "+cid+"\nstart: "+start_num+"\nper_page: "+items_per_page);
			
			// ajax time
			$.post(cur_method, { cid: cid, start: start_num, per_page: items_per_page, code_filter: code_filter }, function(data) {
				// Make sure to comment out when no longer in test mode.. it asplodes IE
				// console.debug(data);
				
				// make button inactive if none left
				if (data.left == 0) {
					$("table.account_history[table="+table_name+"] span.next").addClass("inactive");
				} else {
					$("table.account_history[table="+table_name+"] span.next").removeClass("inactive");
				}
				// use start_num for previous because left counts 0
				if (start_num == 1) {
					$("table.account_history[table="+table_name+"] span.previous").addClass("inactive");
				} else {
					$("table.account_history[table="+table_name+"] span.previous").removeClass("inactive");
				}
				
				// reset cid
				$("form[name=let_there_be_cid] input[name=cid]").val(data.cid);
				
				// conjure up new data
				var table_html = "";
				for (var i in data.transactions) {
					// definte data columns depending on which table this is
					var table_items = new Array();
					if (table_name == "point_transactions") {
						if (data.transactions[i].type_sym == 'SURVEY_TAKEN') {
							table_items = ['Polling', data.transactions[i].point_value, 'Poll', data.transactions[i].created, 'Polling'];
						} else {
							table_items = [type_sym_copy[data.transactions[i].type_sym], data.transactions[i].point_value, data.transactions[i].code_class_description, data.transactions[i].created, data.transactions[i].description];
						}
					} else if (table_name == "redemption_transactions") {
						table_items = [data.transactions[i].description, data.transactions[i].point_value, data.transactions[i].created, data.transactions[i].external_id_2];
					} else if (table_name == "auto_entry") {
						table_items = [data.transactions[i].created, data.transactions[i].external_id_3];
					} else if (table_name == "iw_overlay") {
						table_items = [data.transactions[i].created, data.transactions[i].overlay_name, data.transactions[i].iw_play_link];
					}
					table_html += "<tr>\n";
					// create tds
					for (var z in table_items) {
						// prevent js from writing "undefined" when it gets a null field
						if (table_items[z] == null) {
							table_items[z] = " ";
						}
                	    table_html += "<td>"+table_items[z]+"</td>\n";
					}
               		table_html += "</tr>\n";
				}
				cur_table.children("tbody").html(table_html);
			});
			
			// misc cleanup
			cur_table.attr("start", start_num);
		}
	});
	
	
	// Ticket Examples
	$("#ticket_examples #examples_nav span").click(function() {
		// reset styles
		$("#ticket_examples #examples_nav span").css("text-decoration","underline");
		$("#ticket_examples #examples_nav span").css("cursor","pointer");
		
		// make this link appear clicked
		$(this).css("text-decoration","none");
		$(this).css("cursor","default");
		
		// update example image
		new_example = $(this).attr("example");
		$("#ticket_examples a.modal_trigger").attr("href","display_page?page=ticket_example_"+new_example);
		$("#ticket_examples img").attr("src","public/images/ticket_example_"+new_example+".gif");
	});
	
	
	
	// Commas!
	$(".number").each(function() {
		number = $(this).html();
		number = '' + number;
		number = number.replace(/-/,'');	// bug fix: points spent was reading the hyphen as a character so we are removing all hyphens from the string
		number = number.replace(/\+/,'');	// do the same for plus signs
		if (number.length > 3) {
			var mod = number.length % 3;
			var output = (mod > 0 ? (number.substring(0,mod)) : '');
			for (i=0 ; i < Math.floor(number.length / 3); i++) {
				if ((mod == 0) && (i == 0))
					output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
				else
					output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
				}
			$(this).html(output);
		}
	});
	
	
	// Code Entry Autotabbing
	$('input[name=code_1_1]').autotab({ target: 'code_1_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_1_2]').autotab({ target: 'code_2_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_2_1]').autotab({ target: 'code_2_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_2_2]').autotab({ target: 'code_3_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_3_1]').autotab({ target: 'code_3_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_3_2]').autotab({ target: 'code_4_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_4_1]').autotab({ target: 'code_4_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_4_2]').autotab({ target: 'code_5_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_5_1]').autotab({ target: 'code_5_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_5_2]').autotab({ target: 'code_6_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_6_1]').autotab({ target: 'code_6_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_6_2]').autotab({ target: 'code_7_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_7_1]').autotab({ target: 'code_7_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_7_2]').autotab({ target: 'code_8_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_8_1]').autotab({ target: 'code_8_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_8_2]').autotab({ target: 'code_9_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_9_1]').autotab({ target: 'code_9_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_9_2]').autotab({ target: 'code_10_1', maxlength: 8, format: 'alphanumeric' });
	$('input[name=code_10_1]').autotab({ target: 'code_10_2', maxlength: 3, format: 'alphanumeric' });
	$('input[name=code_10_2]').autotab({ target: 'code_1_1', maxlength: 8, format: 'alphanumeric' });
	
	$('input[name=drawcode_1_1]').autotab({ target: 'drawcode_1_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_1_2]').autotab({ target: 'drawcode_1_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_1_3]').autotab({ target: 'drawcode_2_1', maxlength: 6, format: 'alphanumeric' });

	$('input[name=drawcode_2_1]').autotab({ target: 'drawcode_2_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_2_2]').autotab({ target: 'drawcode_2_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_2_3]').autotab({ target: 'drawcode_3_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_3_1]').autotab({ target: 'drawcode_3_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_3_2]').autotab({ target: 'drawcode_3_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_3_3]').autotab({ target: 'drawcode_4_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_4_1]').autotab({ target: 'drawcode_4_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_4_2]').autotab({ target: 'drawcode_4_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_4_3]').autotab({ target: 'drawcode_5_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_5_1]').autotab({ target: 'drawcode_5_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_5_2]').autotab({ target: 'drawcode_5_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_5_3]').autotab({ target: 'drawcode_6_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_6_1]').autotab({ target: 'drawcode_6_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_6_2]').autotab({ target: 'drawcode_6_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_6_3]').autotab({ target: 'drawcode_7_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_7_1]').autotab({ target: 'drawcode_7_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_7_2]').autotab({ target: 'drawcode_7_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_7_3]').autotab({ target: 'drawcode_8_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_8_1]').autotab({ target: 'drawcode_8_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_8_2]').autotab({ target: 'drawcode_8_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_8_3]').autotab({ target: 'drawcode_9_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_9_1]').autotab({ target: 'drawcode_9_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_9_2]').autotab({ target: 'drawcode_9_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_9_3]').autotab({ target: 'drawcode_10_1', maxlength: 6, format: 'alphanumeric' });
	$('input[name=drawcode_10_1]').autotab({ target: 'drawcode_10_2', maxlength: 4, format: 'alphanumeric' });
	$('input[name=drawcode_10_2]').autotab({ target: 'drawcode_10_3', maxlength: 9, format: 'alphanumeric' });
        $('input[name=drawcode_10_3]').autotab({ target: 'drawcode_1_1', maxlength: 6, format: 'alphanumeric' });

	/* Club Keno Page */
	
	$('#bonus_label').insertAfter('#fs_club_keno_bonus legend');
	$('#jack_label').insertAfter('#fs_club_keno_jack_numbers legend');
	$('#num_label').insertAfter('#fs_club_keno_numbers legend');	
	$('#keno_submit').insertAfter('#fs_club_keno_numbers legend');
	$('#spot_game').insertAfter('#keno_submit');	
	$('#kicker-option-group').insertAfter('#kicker label');
	$('#jack-option-group').insertAfter('#jack label');
	//$('#jack_disclamier').insertAfter('#');
	
	$('input[name=home_phone_number]').keyup(function() {
		$(this).val(FormatPhone($(this).val()));
	});	
	 
    	$('input[name=mobile_phone_number]').keyup(function() {
		$(this).val(FormatPhone($(this).val()));
        });

	/* Winning Numbers Search*/
	$('input[name=raffle_number]').attr("maxlength", "6");
});   

function FormatPhone(str) {
	var sValue = str;
	sValue = Left(sValue.replace(/[^0-9]/ig,""),10);        //remove non numeric values
    	var sLength = sValue.length;
     	switch (sLength){
       		case 0:{
                   	return sValue;
                   	break;}
           	case 1:{
                        return sValue;
                        break;}
            	case 2:{
                        return sValue;
                        break;}
            	case 3:{
                        return sValue;
                        break;}
            	case 4:{
                        return Left(sValue,3) + '-' + Right(sValue,1);
                        break;}
           	case 5:{
                        return Left(sValue,3) + '-' + Right(sValue,2);
                        break;}
            	case 6:{
                        return Left(sValue,3) + '-' + Right(sValue,3);
                        break;}
             	case 7:{
                        return Left(sValue,3) + '-' + Right(Left(sValue,6),3) + '-' + Right(sValue,1);
                        break;}
            	case 8:{
			return Left(sValue,3) + '-' + Right(Left(sValue,6),3) + '-' + Right(sValue,2);
                        break;}
            	case 9:{
			return Left(sValue,3) + '-' + Right(Left(sValue,6),3) + '-' + Right(sValue,3);
                        break;}
              	case 10:{
			return Left(sValue,3) + '-' + Right(Left(sValue,6),3) + '-' + Right(sValue,4);
                        break;}
	}
	return str;
}

function Left(str, n){ 
    if (n <= 0) 
        return ""; 
    else if (n > String(str).length) 
        return str; 
    else 
        return String(str).substring(0,n); 
} 
function Right(str, n){ 
    if (n <= 0) 
       return ""; 
    else if (n > String(str).length) 
       return str; 
    else { 
       var iLen = String(str).length; 
       return String(str).substring(iLen, iLen - n); 
    } 
}

function openWindow(link) {
  window.open(link, '_blank', 'width=800,height=600,toolbar=yes,status=yes,location=yes,menubar=yes,directories=yes,resizable=yes,scrollbars=yes');
}    

function popup(link) {
      popup = window.open(link,'new_popup','menu=no,toolbar=no,width=500px,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
      popup.focus();
}

function update_points(new_point_balance) {
	// take number from flash and comify
	// TO DO: Make comifyer a function so that the code is not duplicated
	number = new_point_balance;
	number = '' + number;
	if (number.length > 3) {
		var mod = number.length % 3;
		var output = (mod > 0 ? (number.substring(0,mod)) : '');
		for (i=0 ; i < Math.floor(number.length / 3); i++) {
			if ((mod == 0) && (i == 0))
				output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
			else
				output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
			}
	} else {
		output = number;
	}
	$("#point_balance").html(output);
}



function instantReplayInfo() {
	window.open("instant_replay_info",this.title,'menu=no,toolbar=no,width=500px,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
}


