//-------------------------------------------------------------------------------
// Front end code for gamebase
// Tim Beck
//-------------------------------------------------------------------------------

var gamebase = (function($) {

	// Build a generic dialog and return the containing div
    var prv_buildDialog = function(id, title, close_text, width, minHeight) {
        minHeight = minHeight || 400;
        
        // Create the dialog if it hasn't been already
        var id =  id + "Dialog";
        var div = $("#" + id);
        if (div.length == 0) {
            $('body').append("<div id='" + id
                             + "' style='display: none'><div id='subscribeProgress'><img src='/images/loader.gif'/></div></div>");
            div = $("#" + id);
            div.dialog({title: title,
                        closeText: close_text,
                        autoOpen: true,
                        modal: true,
                        resizable: false,
                        width: width,
                        minHeight: minHeight 
                       });
        }

        return div;
    };

    // Handle the result of the subscribe request
    var prv_handleSubscribeResult = function(text, status) {
        
        $('#subscribeProgress').hide();
        $('#subscribeFormWrapper').show();

        var result = $($(text)[1]);
        if (result.is(".dialogError")) {
            prv_showError('subscribeResult', result.html());
        } else {
            $('#subscribeFormWrapper').hide();
            $('#subscribeResult').html(text).show();
            $('#subscribeClose').show();
        }
    };
    
    // Handle the result of the deactivate request
    var prv_handleDeactivateResult = function(text, status) {
        
        $('#subscribeProgress').hide();
        $('#deactivateFormWrapper').show();

        var result = $($(text)[1]);
        if (result.is(".dialogError")) {
            prv_showError('deactivateResult', result.html());
        } 
        else if (result.is(".subscribeSuccess")) {
        	$('#deactivateDialog').dialog('close');
            location.reload();
        }
        else {
            $('#deactivateFormWrapper').hide();
            $('#deactivateResult').html(text).show();
            $('#deactivateClose').show();
        }
    };
    
 // Handle the result of the vet request
    var prv_handleVetResult = function(text, status) {
        
        $('#subscribeProgress').hide();
        $('#vetFormWrapper').show();

        var result = $($(text)[1]);
        if (result.is(".dialogError")) {
            prv_showError('vetResult', result.html());
        } 
        else if (result.is(".subscribeSuccess")) {
        	$('#vetDialog').dialog('close');
            location.reload();
        }
        else {
            $('#vetFormWrapper').hide();
            $('#vetResult').html(text).show();
            $('#vetClose').show();
        }
    };
    
    var prv_handleReassignResult = function(text, status) {
        
        $('#subscribeProgress').hide();
        $('#reassignFormWrapper').show();

        var result = $($(text)[1]);
        if (result.is(".dialogError")) {
            prv_showError('reassignResult', result.html());
        } 
        else if (result.is(".subscribeSuccess")) {
        	$('#reassignDialog').dialog('close');
            location.reload();
        }else{
            $('#reassignFormWrapper').hide();
            $('#reassignResult').html(text).show();
            $('#reassignClose').show();
        }
        
    };
    
    var prv_showError = function(id, text) {
        $('#' + id).html('<div class="dialogError">' + text + '</div>').show().effect('highlight', {color: '#bd1e2c'}, 500);
    }
    
    // Public Interface
    return {

        // Email subscription methods
        showSubscribeDialog: function(productId, pd_title, pd_close, country_prefix) {
            // Create the dialog if it hasn't been already
            var div = prv_buildDialog('subscribe', pd_title, pd_close, 420, 300);
            div.html('<div id="subscribeProgress"><img src="/images/loader.gif"/></div>');
            div.dialog('open').load('/email_notifications.php?product_id=' + productId,
                                    '',
                                    function() {
                                        gamebase.styleButton($('#subscribeSubmitButton'), 'subscribe', country_prefix);
                                    });
        },
        submitSubscribeForm: function() {
            // Set the UI
            $('#subscribeFormWrapper').hide();
            $('#subscribeProgress').show();
            $('.dialogError').hide();
            // Send the request
            var form = $('#subscribeForm');
            $.post(form.attr('action'),
                   form.serialize(),
                   prv_handleSubscribeResult
			);
		},
        
        
        // Product flag methods
        showFlagDialog: function(manuId, productId, pf_title, pf_close, country_prefix) {
            
            // Set the parameter defaults to empty string
            manuId = manuId || "";
            
            var div = prv_buildDialog('flag', pf_title, pf_close, 420, 370);
            div.dialog('open').load('/flag_product.php?merchant_product_id='+manuId
                                    + '&product_id=' + productId,
                                    '',
                                    function() {
                                        gamebase.styleButton($('#flagSubmitButton'), 'submit', country_prefix);
                                    });
        },
		submitFlagForm: function() {
            // Send the request
            var form = $('#flagForm');
            $.post(form.attr('action'),
                   form.serialize(),
                   function() { /* don't care */ });
            // Close the dialog
            $('#flagDialog').dialog('close');
        },
        
        // Admin Flag Method
        showAdminFlagDialog: function(full_flag_id, flagReason, pd_close) {
            // Create the dialog if it hasn't been already
            var div = new prv_buildDialog('flag' + full_flag_id, flagReason, pd_close, 420, 400);
            // Create the dialog if it hasn't been already
            div.html('<div id="subscribeProgress"><img src="/images/loader.gif"/></div>');
            div.dialog('open').load('/flag_admin.php?full_flag_id=' + full_flag_id,
                                    '',
                                    function() {
                                        gamebase.styleButton($('#flagSubmitButton'), 'submit', 'UK');
                                    });
        },
        
        // Admin Vet Methods
        showAdminVetDialog: function(product_id) {
        	var result = "";   
        	var mp_list = 'false';                        
			$(".reassign_check").each( function () {
				if(this.checked == true) {
					result += $(this).attr("name") + "+";
					mp_list ='true';
				}
			});
			if(mp_list=='true') {
				result = $.trim(result);
				result = result.replace(/ /g,',');
	            // Create the dialog if it hasn't been already
	            var div = new prv_buildDialog('vet', 'Vet', 'CLOSE', 420, 400);
	            // Create the dialog if it hasn't been already
	            div.html('<div id="subscribeProgress"><img src="/images/loader.gif"/></div>');
	            div.dialog('open').load('/vet_admin.php?product_id=' + product_id + '&merchant_product_ids=' + result ,
	                                    '',
	                                    function() {
	                                        gamebase.styleButton($('#flagSubmitButton'), 'submit', 'UK');
	                                    });
	        	}
        },
		submitVetForm: function() {
            // Set the UI
            $('#vetFormWrapper').hide();
            $('#subscribeProgress').show();
            $('.dialogError').hide();
            // Send the request
            var form = $('#vetForm');
            $.post(form.attr('action'),
                   form.serialize(),
                   prv_handleVetResult);
		},
        
        // Admin Deactivate Methods
        showAdminDeactivateDialog: function(product_id) {
        	var result = "";   
        	var mp_list = 'false';                        
			$(".reassign_check").each( function () {
				if(this.checked == true) {
					result += $(this).attr("name") + "+";
					mp_list ='true';
				}
			});
			if(mp_list=='true') {
				result = $.trim(result);
				result = result.replace(/ /g,',');
	            // Create the dialog if it hasn't been already
	            var div = new prv_buildDialog('deactivate', 'Deactivate', 'CLOSE', 420, 400);
	            // Create the dialog if it hasn't been already
	            div.html('<div id="subscribeProgress"><img src="/images/loader.gif"/></div>');
	            div.dialog('open').load('/deactivate_admin.php?product_id=' + product_id + '&merchant_product_ids=' + result ,
	                                    '',
	                                    function() {
	                                        gamebase.styleButton($('#flagSubmitButton'), 'submit', 'UK');
	                                    });
	        	}
        },
		submitDeactivateForm: function() {
            // Set the UI
            $('#deactivateFormWrapper').hide();
            $('#subscribeProgress').show();
            $('.dialogError').hide();
            // Send the request
            var form = $('#deactivateForm');
            $.post(form.attr('action'),
                   form.serialize(),
                   prv_handleDeactivateResult);
		},
        
        
		// Admin - Reassign Methods
        showAdminReassignDialog: function(product_id) {
        	var result = "";      
        	var mp_list = 'false';                    
			$(".reassign_check").each( function () {
				if(this.checked == true) {
					result += $(this).attr("name") + "+";
					mp_list ='true';
				}
			});
			if(mp_list=='true') {

				result = $.trim(result);
				result = result.replace(/ /g,',');
	            // Create the dialog if it hasn't been already
	            var div = new prv_buildDialog('reassign', 'Reassign', 'CLOSE', 600, 400);
	            // Create the dialog if it hasn't been already
	            div.html('<div id="subscribeProgress"><img src="/images/loader.gif"/></div>');
	            div.dialog('open').load('/reassign_admin.php?product_id=' + product_id + '&merchant_product_ids=' + result ,
	                                    '',
	                                    function() {
	                                        gamebase.styleButton($('#flagSubmitButton'), 'submit', 'UK');
	                                    });
			}
        },
		submitReassignForm: function() {
			if ($(".reassign_search_select").val() !=''){
	            // Set the UI
	            $('#reassignFormWrapper').hide();
	            $('#subscribeProgress').show();
	            $('.dialogError').hide();
	            // Send the request
	            var form = $('#reassignForm');
	            $.post(form.attr('action'),
	                   form.serialize(),
	                   prv_handleReassignResult);
	      		}
		},
		submitSearchForm: function() {
            if ($(".reassign_search_box").val() != ''){
	            // Set the UI
            	$('#reassignFormWrapper').hide();
	            $('#subscribeProgress').show();
	            $('.dialogError').hide();
	            // Send the request
            	var form = $('#reassignForm');
	            $.post(form.attr('action'),
	                   form.serialize(),
	                   prv_handleReassignResult);
			}
		},
		
		
		//Admin - Edit Title 
       	EditTitle: function(product_id) {
	     $(".productDetailTitle #EditTitleButton").text("Save");
         $("#editTitle").removeAttr('readonly');
	     $("#editTitle").focus();
	     $(".productDetailTitle #EditTitleButton").removeAttr('onclick').bind("click",function(){
				var url="/flag_admin.php";
				var encoded_title = escape(encodeURI($(".productDetailTitle #editTitle").val()));
				var data="product_id=" + product_id + "&title=" + encoded_title; 
				$.post(url,data,function(data,status){
					if (data==1){
						$(".productDetailTitle #EditTitleButton").text("Saved");
						$("#editTitle").attr('readonly', 'readonly');
						var new_title = $.trim($(".productDetailTitle #editTitle").val());
						alert("The new product Url is '" + new_title.replace(/\W+/g,'-') + "'");
					}else{
						$(".productDetailTitle #EditTitleButton").text("Failed");
					}
				});
			});
        },

	//Admin - Edit Description
        EditDesciption: function(product_id, country_id) {
	     $(".productDetailDesc #EditDescButton").val("Save");
         $("#editDescription").removeAttr('readonly');
	     $("#editDescription").focus();
	     $(".productDetailDesc #EditDescButton").removeAttr('onclick').bind("click",function(){
				var url="/flag_admin.php";
				var encoded_description = escape(encodeURI($("#editDescription").val()));
				var data="product_id=" + product_id + "&description_override=" + encoded_description;
				$.post(url,data,function(data,status){
					if (data==1){
						$(".productDetailDesc #EditDescButton").val("Saved");
						$("#editDescription").attr('readonly', 'readonly');
					}else{
						$(".productDetailDesc #EditDescButton").val("Failed");
					}
				});
			});
        },

		//Admin - Clear Flag
		ClearFlag: function(clear_id){
			var wdo = "flag" + clear_id + "Dialog";
	       	var div = $("#" + wdo);
			$("." + clear_id).remove();
			var url="/flag_admin.php";
			var data="flag_clear_id=" + clear_id;
			$.post(url,data);
			div.dialog('close');
		},
	
		//Admin - Goto Admin page
		GotoAdmin: function(merchant_product_id,product_id,clear_id){
			if (merchant_product_id == 0){
				url = '../admin/products?product_id=' + product_id;
			}else{
				url = '../admin/merchant_products?merchant_product_id=' + merchant_product_id;
			}
			var wdo = "flag" + clear_id + "Dialog";
	       	var div = $("#" + wdo);
			div.dialog('close');
			window.open(url);
		},
	
		//Admin - send email
		Report: function(clear_id){
			var wdo = "flag" + clear_id + "Dialog";
	       	var div = $("#" + wdo);
			var url="/flag_admin.php";
			var data="report=" + clear_id;
			$.post(url,data);
			div.dialog('close');
		},
		
		//Admin - deactivate product
		deactivateProduct: function(product_id){

			var encoded_title = $(".productDetailTitle #editTitle").val();
			var div = $("#confirm_dialog" );
			$('body').append("<div id='" + "confirm_dialog" + "' style='display: none'><div style='font-size:14px'></br></br>Are you sure you want to deactivate</br>" + encoded_title + "?</div></div>");
           	div = $("#confirm_dialog" );
        	div.dialog({	
        		title: "Confirm Deactivate",
         		closeText: "",
     			autoOpen: true,
				modal: true,
				resizable: false,
				buttons: {
					"Cancel": function() {
						$(this).dialog("close");
					},
					"Deactivate": function() {
						var url="/flag_admin.php";
						var data="deactivate_product_id=" + product_id;
						$.post(url,data,
							function(data,status){
								$(this).dialog("close");
								location.reload();
							}
						);
						redirect_url = '../admin/products?product_id=' + product_id;
						window.open(redirect_url);
					}
				}
        	});
			div.dialog('open');
		},
		
		//Admin - vet product
		vetProduct: function(product_id){

			var encoded_title = $(".productDetailTitle #editTitle").val();
			var div = $("#confirm_dialog" );
			$('body').append("<div id='" + "confirm_dialog" + "' style='display: none'><div style='font-size:14px'></br></br>Are you sure you want to vet</br>" + encoded_title + "?</div></div>");
           	div = $("#confirm_dialog" );
        	div.dialog({	
        		title: "Confirm Vetting",
         		closeText: "",
     			autoOpen: true,
				modal: true,
				resizable: false,
				buttons: {
					"Cancel": function() {
						$(this).dialog("close");
					},
					"Vet": function() {
						var url="/flag_admin.php";
						var data="vet_product_id=" + product_id;
						$.post(url,data,
							function(data,status){
								$(this).dialog("close");
								location.reload();
							}
						);
					}
				}
        	});
			div.dialog('open');
		},

		//Admin - Update Prices
		updatePrices: function(product_id,path){
				var div = $("#update_dialog" );
		     	$('body').append("<div id='update_dialog' style='display: none'><div></br></br><img src='/images/loader.gif' height='70px'/></div></div>");
		     	div = $("#update_dialog" );
	            div.dialog({	title: "Updating Prices",
	                        	closeText: "",
	                        	autoOpen: true,
	                        	modal: true,
	                        	resizable: false
	                       });
			var data="update_prices_product_id=" + product_id;
			$.post(path,data,function(data,status){
					var data1="initiate_sphinx_update=true";
					$.post(path,data1,function(data,status){
							$("#ui-dialog-title-update_dialog").text("Updating Sphinx");
							$("#update_dialog").append("</br>Will take up to 30 seconds + the last run time of " + data + " seconds" );
							setTimeout("gamebase.check_sphinx_update_status('" + path + "')",5000);
						});
				});
		},												
		
		check_sphinx_update_status: function(path){
			var data="sphinx_update_status=true";
			$.post(path,data,function(data,status){
				if(data=="idle"){
					$("#update_dialog").dialog("close");
					location.reload(); 
				}else{
					$("#ui-dialog-title-update_dialog").text("Updating Sphinx - " + data);
					setTimeout("gamebase.check_sphinx_update_status('" + path + "')",2000);
				}
			});
		},

		showFullChart: function(productId, pd_title, pd_close, country_prefix) {
            // Create the dialog if it hasn't been already
            var div = prv_buildDialog('chart', pd_title, pd_close, 750, 350);
            div.html('<div><img  style="position: absolute;" src="/images/loader.gif" height="70px"/></div>');
            div.dialog('open').load('/chart.php?product_id=' + productId,
                                    '',
                                    function() {
                                        //gamebase.styleButton($('#subscribeSubmitButton'), 'subscribe', country_prefix);
                                    });
        },

        styleButton: function(element, prefix, country_prefix) {

            element.hover(
                function() {
                    $(this).css('backgroundImage', 'url(/images/' + country_prefix + '/' + prefix + '_hover.png)');
                },
                function() {
                    $(this).css('backgroundImage', 'url(/images/' + country_prefix + '/' + prefix + '_normal.png)');            
                }
            )
            .bind('mousedown', function() { $(this).css('backgroundImage','url(/images/' + country_prefix + '/' + prefix + '_active.png)'); })
            .bind('mouseup', function() { $(this).css('backgroundImage','url(/images/' + country_prefix + '/' + prefix + '_hover.png)'); });
        }
    };

})(jQuery);

    

