/**
 * tft membership
 * Author: David Wright, Develop Wright LLC
 */

var ajax_url = 'wp-content/themes/ft/inc/ajax_controller.php';
var tft_selected_plan = null;
var tft_selected_section = null;
var tft_selected_section_id = null;
var tft_selected_writer = null;
var selected_color = "#F5FFEB";

// Set this to blog_id of the all_correspondents section
var all_correspondents = 1;

/**
 * Initialize Membership Plans Page
 */
$(document).ready(function($) {

	// Plan Page    
	
	// set choose this plan event handler
	$(".plan-link").livequery('click', function(event) {
        tft_selected_plan = event.target.id.substring(4,5);

		// update session variable and message to user
		var d = {
				action: 'set_selected_plan',
				plan_id: tft_selected_plan
			}

			$.ajax({
				url: ajax_url,
				data: d,
				cache: false,
				type: 'get',
				dataType: 'text',
				contentType: 'text/html',
				success: function(response) {
                    window.location = 'membership-writers';
				},
				error: function (XHR, textStatus, errorThrown) {
					alert(errorThrown);
				}
			});
	});

	// load event handlers - WRITERS

	// ** VIEW BY SECTION TABS: CLICK
	$(".h-tab li").livequery('click', function(event) {

		$('#tft-writers').html('<div id="loading">Loading...</div>');

		tft_selected_section_id = event.target.id;

		// Set the selected section
		tft_selected_section = $(this).text();

		// Highlight the currently selected
		$(this).css("background-color","#000000");
		$(this).css("color","#FFFFFF");

		// Reset all the others to not selected
		$(".h-tab li").each(function() {
			if ($(this).text() != tft_selected_section) {
				$(this).css("background-color","#B7C2C8");
				$(this).css("color","#56575B");
			}
		});

		writer_search.reset();

		get_writers({
			'mode' : 'available',
			'section' : tft_selected_section_id
		});

	});

	// ** VIEW BY SECTION TABS: HOVER
	$(".h-tab li").livequery(function(){
		// use the helper function hover to bind a mouseover and mouseout event
			$(this)
				.hover(function() {
					$(this).css("background-color","#777777");
					$(this).css("color","#FFFFFF");
				}, function() {
					$(this).css("background-color","#B7C2C8");
					$(this).css("color","#56575B");

					// reselect the currently selected
					if (tft_selected_section != null) {
						$(".h-tab li:contains('" + tft_selected_section + "')").css("background-color","#000000");
						$(".h-tab li:contains('" + tft_selected_section + "')").css("color","#FFFFFF");
					} else {
						var ac = $("#" + all_correspondents);
						ac.css("background-color","#000000");
						ac.css("color","#FFFFFF");
					}
				});
		}, function() {
			// unbind the mouseover and mouseout events
			$(this)
				.unbind('mouseover')
				.unbind('mouseout');
		});


		//------- CHOOSE WRITER: SEARCH -------
		var ms = $(".m-search");

		// Search button
		ms.livequery('click', function() {
			ms.val('');
			ms.css("color","#000000");
		});

		// Search Box
		ms.livequery('blur', function() {
			if (ms.val() == "") {
				ms.css("color","#777777");
				ms.val("Search");
			}
		});

        // Search button clicked
		$(".m-search-go").livequery('click', function(event) {

			if (!writer_search.check_val()) { return false; }
			get_writers({
				'mode' : 'available',
				'search_term' : writer_search.get_val(),
				'section' : tft_selected_section_id
			});
		});

		$('#m-search-term').livequery('keyup', function(e) {

			if (!writer_search.check_val()) { return false; }

			if(e.keyCode == 13) {
				get_writers({
					'mode' : 'available',
					'search_term' : writer_search.get_val(),
					'section' : tft_selected_section_id
				});
			}
		});

		
        init_available_writer_events();

		// ** SELECTED WRITERS: CLICK
		$(".remove-writer").livequery('click', function(event) {

			tft_ajax({
				action: 'writer_remove',
				uid: event.target.id,
				dataType: 'json'
			});
		});


		// ** CHANGE WRITER BUTTION: CLICK
		$("#change-writer").livequery('click', function() {

			// Show writer search / section section
			$("#writer-section").css("display", "block");

			// repopulate available writers
			get_writers({'mode':'available'});
			
			// hide the change writer button
			$("#change-writer").css("display", "none");

		});


  		// initialize continue button actions
		button_actions('.continue-button-div');



		//-------------------------------------------------------------------------

		// ** Initialize View By Section Menu
		// Select the all correspondents tab if no section is selected
		if (tft_selected_section_id == null) {
			// Reset all tabs to not selected
			$(".h-tab li").each(function() {
				$(this).css("background-color","#B7C2C8");
				$(this).css("color","#56575B");
			});

			// default the section menu to All
			var ac = $("#" + all_correspondents);
			ac.css("background-color","#000000");
			ac.css("color","#FFFFFF");
		}


		// ** Initalize Search Box
		writer_search.reset();

		//-------------------------------------------------------------------------

		/**
		 * Page: membership-gift
		 * unclick no gift if any other gift is clicked
         * unclick all other gifts if no gift is clicked
         * prevent more than gift_limit from being clicked
         */
         
		$(".gifts").livequery('click', function(event) {

		    // unclick no gift if any other gift is clicked
		    // unclick all other gifts if no gift is clicked

            var max = $("#gift_limit").val();
            var count = 0;

            if (event.target.value == 'None') {
                $("input[@name='gifts[]']:checked").each(function() {
                    
                    if ($(this).val() != 'None') {
                    
                        $(this).attr('checked', false);
                    }
                });
            
            } else {
            
                $("input[@name='gifts[]']:checked").each(function() {

                    if ($(this).val() == 'None') {
                        $(this).attr('checked', false);
                    } else {
                        count = count + 1;
                    }

                    if (count > max) {
                        $(this).attr('checked', false);
                        alert('You can only select ' + max + ' gifts.');
                        count = count - 1;
                    }                
                });
            }
		});
		
});

function init_available_writer_events() {

    //------- LIST OF WRITERS: HOVER -------
    for (i = 1; i <= 3; i++) {
    
        var column = ".low-col" + i;
    
        // Set handlers
        $(column).livequery(function() {
        	$(this)
        		.hover(function() {
        			$(this).css("background-color", "#B7C2C8");
        		}, function() {
        			if ($(this).hasClass("alt-row")) {
        				$(this).css("background-color", "#EFEFEF");
        			} else {
        				$(this).css("background-color", "#FFFFFF");
        			}
        		});
        }, function() {
        	// unbind the mouseover and mouseout events
        	$(this)
        		.unbind('mouseover')
        		.unbind('mouseout');
        });
    
        // ** LIST OF WRITERS: CLICK
        $(column).livequery('click', function(event) {
        	if (event.target.id) {
        		tft_selected_writer = 1;
        		tft_ajax({
        			action: 'set_selected_writer',
        			data: event.target.id
        		});
        	}
        });
    }
}

/**
 * Main function to return writer HTML
 * input:
 *		action = the ajax controller function to call
 *		section = the selected blog id, defaults to all
 *		mode = available | selected
 *
 *	Updates the corresponding HTML block with writers
 */
function get_writers(data) {

	$('#tft-writers').html('<div id="loading">Loading...</div>');

	data.action = 'get_writers_xhr';

	if (tft_selected_section_id != null) {
		data.section = tft_selected_section_id;
	}

	var div_to_update = (data.mode == 'available') ? '#tft-writers' : '#selected-writer';
	
	if (data.mode != 'available') {
    	$(div_to_update).css("display","block");
    }

	$.ajax({
		url: ajax_url,
		data: data,
		type: 'get',
		dataType: 'text',
		contentType: 'text/html',
		success: function(response) {
			$(div_to_update).html(response);
			
			if (data.mode == 'available') {
    			init_available_writer_events();
            }
		},
		error: function(XHR, textStatus, errorThrown) {
			alert(errorThrown);
		}
	});
	
}


/*------------------------------------------------------------------------------
 * Set event listener for membership page continue buttons
 * Verifies current page requirements are met before allowing continue
 *-----------------------------------------------------------------------------*/
function button_actions(class_name) {

    $(class_name).livequery('click', function(event) {
    
        event.preventDefault(); // stop default browswer behavior
        
        var children = $(class_name).children();
        var link_name = children.attr('name');
        
        var msg = "";
        var show_alert = false;

        switch (link_name) {
           
            case 'membership-writers':
                show_alert = (tft_selected_plan == null) ? true : false;
                msg = "You must select a plan to continue.\nClick the \"OK\" button to close this window.";

                if (show_alert) {
                    alert(msg);
                } else {
                    window.location = link_name;
                }
                
                break;
                
            case 'membership-gift':
                show_alert = (tft_selected_writer == null) ? true : false;
                msg = "You must select a writer to continue.\nClick the \"OK\" button to close this window.";

                if (show_alert) {
                    alert(msg);
                } else {
                    window.location = link_name;
                }
                
                break;
                
            case '/subscription/signup.php':
                
                // check for at least one selected gift
                var check_num = 0;
                var g = new Array();
                $("input[@name='gifts[]']:checked").each(function() {
                    check_num = check_num + 1;
                    if ($(this).val() != 'on') {
                        g.push($(this).val());
                    }
                });
                
                if (check_num == 0) {
                    show_alert = true;
                    msg = 'You didn\'t choose a gift. If you don\'t want one, click the "No Gift" option.';
                    alert(msg);
                
                } else {

                    //:: removed terms of service- this was broken before that
                    //show_alert = ($('#agreement:checked').val() != null) ? false : true;
                    //msg = 'You must agree to Terms of Service to have a membership plan for The Faster Times.';

                    
                    // Update session variable with selected gifts and check to see if user is logged in
                    $.ajax({
                        url: ajax_url,
                        data: {
                            action : 'set_gift',
                            gifts  : g.join("|")
                        },
                        dataType: "text",
                        success: function(response) {
                            var logged_in = response.substring(0,1);
                            
                            // if no alerts and XHR response indicates they are logged in then go                       
                            if (!show_alert) {
                                if (logged_in != "1") {
                                    window.location = '/wp-signup.php?mm=1';
                                } else {
                                    window.location = link_name;
                                }
                            }
                        
                        }
                    });
                }
                
                break;
        }
    });
}



function tft_ajax(data) {

	//data.data = (!data.data) ? "" : data.data;
	data.dataType = (!data.dataType) ? "text" : data.dataType;

	$.ajax({
		url: ajax_url,
		data: data,
		dataType: data.dataType,
		success: function(response) {

			if (data.action) {
				switch (data.action) {

					case 'set_selected_writer':

						$('.selected-writer-block').html('<div style="text-align:center; padding: 10px;">Loading...</div>');
						//update/show selected writer block
						get_writers({mode: 'selected'});

						//hide available writer stuff
						//$("#writer-section").css("display", "none");
						get_writers({mode:'available'});
						
						$("#goto-gifts").css("display", "inline");
						break;

					case 'writer_remove':

						if (response.show) {
							get_writers({mode: 'selected'});
							
							if ($("tft-writers").css("display") == "block") {
								get_writers({mode: 'available'});

							}
						} else {

							tft_selected_writer = null;
							$("#selected-writer").css("display","none");
							$("#writer-section").css("display", "block");
							get_writers({mode: 'available'});

						}
						break;

					default:
						break;
				}
			}
		},
		error: function (XHR, textStatus, errorThrown) {
			alert(errorThrown);
		}
	});
}


// + Writer Search Functions
var writer_search = {

	get_val: function() {
		return $("#m-search-term").val();
	},

	check_val: function() {
		var st = $("#m-search-term").val();
		if (st == "" || st == "Search") {
			return false;
		}
		return true;
	},

	reset: function() {
		var ms = $(".m-search");
		ms.val("Search");
		ms.css("color","#777777");
	}
}



// !tft_membership
/*------------------------------------------------------------------------------
 * Modal Windows:
 * Login Box
 * Incomplete Requirements Box
 *-----------------------------------------------------------------------------*/
var tft_membership = {
    light_box_helper: function(data) {
		$(document).ready(function($) {
			lb_createWindow( 
				data.boxid,
				data.title,
				jQuery(data.source),
				parseInt($(data.source).attr("width")),
				parseInt($(data.source).attr("height"))
			);
			return;
		});
    },
	show_login: function() {
       this.light_box_helper({
            boxid  : 'loginbox',
            title  : 'login box',
            source : '#loginbox'
        });	
	},
	show_incomplete: function() {
		this.light_box_helper({
			boxid  : 'incompletebox',
			title  : 'Select Plan and/or Writer',
			source : '#incompletebox'
		});
	}
}


// !tft_plans
var tft_plans = {

	init: function() {

		$('.plan').each(function() {
			var id = this.id.substring(4,5);
			var bgcolor;
			if (id == tft_selected_plan) {
				//bgcolor =  "#B7C2C8";
				bgcolor = selected_color;
			} else {
				bgcolor =  "#EFEFEF";
			}

			$(this).css("background-color", bgcolor);
		});


		$(".plan").hover(
			function() {


				$(this).css("background-color", "#F9FCFF");

				if (tft_selected_plan != "") {
					$('.plan').each(function(){
						var id = this.id.substring(4,5);

						if (id == tft_selected_plan) {
							$(this).css("background-color",selected_color);
						}

					});
				}
			},
			function() {

				$(this).css("background-color", "#EFEFEF");

				if (tft_selected_plan != "") {
					$('.plan').each(function(){
						var id = this.id.substring(4,5);

						if (id == tft_selected_plan) {
							$(this).css("background-color",selected_color);
						}

					});
				}
			});

		$(".plan").click(function(event) {

			var planid = event.target.id.substring(4,5);

			tft_plans.set_selected_plan(planid);
		});

	},

	set_selected_plan: function(selected_index) {

		if (!selected_index || selected_index == null ) { return 'missing plan id'; }

		tft_selected_plan = selected_index;
		
		// Turn off the non selected and turn on the selected
		$('#planid' + selected_index).css("background-color", selected_color);

		$(".plan").each(function() {

			var id = this.id.substring(4,5);

			if (id != tft_selected_plan) {
				$(this).css("background-color","#EFEFEF");
			}
		});

		// update session variable and message to user
		var d = {
				action: 'set_selected_plan',
				plan_id: tft_selected_plan
			}

			$.ajax({
				url: ajax_url,
				data: d,
				cache: false,
				type: 'get',
				dataType: 'text',
				contentType: 'text/html',
				success: function(response) {
					$('#youve_selected_plan').html('YOU HAVE SELECTED THIS HIGHLIGHTED PLAN:');
				},
				error: function (XHR, textStatus, errorThrown) {
					alert(errorThrown);
				}
			});
	}
}

function set_selected_section(text) {

    // Reset all the others to not selected
    $(".h-tab li").each(function() {
        if ($(this).text().toUpperCase() != text.toUpperCase()) {
        	$(this).css("background-color","#B7C2C8");
        	$(this).css("color","#56575B");
        } else {
    		// Highlight the currently selected
    		$(this).css("background-color","#000000");
    		$(this).css("color","#FFFFFF");			
        }
    });
}

