/* 
 * @About      : Javascript file for custom jQuery functions.
 * @File       : jquery.autometers.css
 * @Version    : 1.0
 */

// Fancybox settings -- so it's easy to keep it all consistent. 
//		The 'modal' setting turns off the X button, the ability to hit 
//		Escape and clicking anywhere off the popup to close it -- allows us to keep control of the process.				

arr_FancyBoxSettings = 
{ 
    'modal'		: false    ,
    'titleShow'		: false    ,
    'transitionIn'	: 'fade'    ,
    'transitionOut'	: 'fade'    ,
    'onCleanup'		: jQuery_AJAXCall_SubmitBasket_RefreshBasketLink
};

jQuery(document).ready(function() {
    (function($) {
        jQuery_SwitchList_Setup();
        jQuery_AJAXCalls_BindAll();
        jQuery_MenuHover_Setup();
        jQuery_Thumbnails();
        jQuery_Search_Setup();
        jQuery_Setup_QuoteMaker();
    })(jQuery);
});

(function($){$.fn.jScroll=function(d){var e=$.extend({},$.fn.jScroll.defaults,d);return this.each(function(){var a=$(this);var b=$(window);var c=new location(a);b.scroll(function(){a.stop().animate(c.getMargin(b),e.speed)})});function location(c){this.min=c.offset().top;this.max=c.parent().height()-c.outerHeight();this.originalMargin=parseInt(c.css("margin-top"));this.getMargin=function(a){var b=this.originalMargin;if(a.scrollTop()>=this.min)b=b+e.top+a.scrollTop()-this.min;if(b>this.max)b=this.max;return({"marginTop":b+'px'})}}};$.fn.jScroll.defaults={speed:"slow",top:10}})(jQuery);

(function($) {
    $.fn.toggleFade = function(settings)
    {
        settings = jQuery.extend(
        {
            speedIn: "normal",
            speedOut: settings.speedIn
        }, settings
        );
        return this.each(function()
        {
            var isHidden = jQuery(this).is(":hidden");
            jQuery(this)[ isHidden ? "fadeIn" : "fadeOut" ]( isHidden ? settings.speedIn : settings.speedOut);
        });
    };
})(jQuery);

function jQuery_Setup_QuoteMaker()
{
    //$(".QuoteSummaryScroll").jScroll();
    jQuery_Setup_ProductPick();
    //jQuery_Handle_CopyDeliveryCost();
    //jQuery_Setup_QuoteSummaryScroll();

    // Reset button for Step 1
    $('#button_ClearCustomer').click(function() {
       $('input[name^="CustomersModel"]').val(""); 
    });

    // Spare parts / New Products setup
    $('img.button_SpareParts').click(function() { 
       var el_Row = $(this).parent().parent();
       var el_RowNext = $(this).parent().parent().next(); // Get the table row container 
       $(el_Row).addClass("selected");
       $("td", el_RowNext).toggleClass("hidden");
    });

    // Spare Part - Copy textarea to the applicable hidden input
    $('.button_SparePartSave').click(function() {
        var el_ParentTD = $(this).parent().parent();
        var el_RowPrevious = $(this).parent().parent().parent().prev();

        var val_SpareParts = $("#product_spareparts", el_ParentTD).val();
        $("#OrderProductsModel_product_spareparts", el_RowPrevious).val(val_SpareParts);
        $(el_ParentTD).toggleClass("hidden");
    });

    // Spare Part - Clear the input boxes & hide textarea
    $('.button_SparePartCancel').click(function() {
        var el_ParentTD = $(this).parent().parent();
        $("#product_spareparts", el_ParentTD).val("");
        $(el_ParentTD).toggleClass("hidden");
    });

    // Update Customer button on Quote Summary - clears form, gets correct details and goes to Step 1
    $('.button_UpdateCustomerQuote').livequery('click', function() {
        // Populate form with correct details
        var el_Row = $(this).parent().parent();
        var int_Customer_Id = "";
        if ($("#CustomerOrdersModel_customer_id", el_Row))
        {
            int_Customer_Id = $("#CustomerOrdersModel_customer_id", el_Row).val();
        }
        jQuery_QuoteMaker_PopulateCustomer(int_Customer_Id);
        
        // Show the file uploader
        $("#form_FileUpload").fadeIn();

        // Show form
        $("#form_QuoteMaker").formwizard("show","step1_Customers"); 
    });

    // Add Customer button on Quote Summary - clears form, goes to Step 1
    $('.button_AddCustomerQuote').livequery('click', function(e) {
        e.preventDefault();
        $(':input', $("#step1_Customers"))
            .not(':button, :submit, :reset')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        $("#form_QuoteMaker").formwizard("show","step1_Customers");

        // Show the file uploader
        $("#form_FileUpload").fadeIn();
    })

    // Add Customer button on Quote Summary - clears form, goes to Step 2
    $('.button_AddProduct').livequery('click', function(e) {

        e.preventDefault();
        // Show the file uploader
        $("#form_FileUpload").fadeIn();

        $("#form_QuoteMaker").formwizard("show","step2_Products"); 
    })

    // Add Customer button on Quote Summary - clears form, goes to Step 3
    $('.button_UpdateQuote').livequery('click', function(e) {
        e.preventDefault();
        $("#form_QuoteMaker").formwizard("show","step3_QuoteDetails"); 
    });

    $('.clickClear').livequery('click', function() {
        $(this).val("");
    });

    $('.button_RemoveDocument').livequery('click', function(e) {
        e.preventDefault();
        jQuery.ajax({
            type	: "GET",
            cache	: false,
            dataType    : "json",
            url         : $(this).attr('href'),
            success: function(response) {
                if (response.success)
                {
                    // Update the Preview Pane
                    jQuery_AJAXCall_QuoteMakerSummary(false);
                    return true;
                } else {
                    alert(response.message);
                    return false;
                }
            }
        });
    });

    // Customer remove from Quote button
    $('.button_RemoveProduct').livequery("click", function() {
        var el_Row = $(this).parent().parent();        
        var str_QueryString = $(":input", el_Row).serialize();
        jQuery.ajax({
            type	: "POST",
            cache	: false,
            dataType    : "json",
            url         : "/ajax/QuoteProductRemove",
            data	: str_QueryString,
            success: function(response) {
                if (response.success) 
                { 
                    // Update the Preview Pane
                    jQuery_AJAXCall_QuoteMakerSummary(false);    
                    // Update both Step2 & Step3 & Step4 product listing
                    $("input#step2_QuoteProduct_Ids,input#step3_QuoteProduct_Ids,input#step4_QuoteProduct_Ids").val(response.QuoteProduct_Ids);
                    return true;
                } else {
                    alert(response.message);
                    return false;
                }                
            }
        });  
        
    });

    // Form Wizard
    $("#form_QuoteMaker").formwizard({ 
        formPluginEnabled: true,
        validationEnabled: true,
        focusFirstInput : true,
        disableUIStyles : true,
        remoteAjax : {
            "step1_Customers" : 
            {
                url : "/ajax/QuoteCustomers", 
                dataType : "json",
                success : function(response)
                {
                    if (response.success) 
                    { 

                        // Add response message to Step 2 title
                        //alert(response.message);
                        
                        // Add the Customer details to the Step 2 form, so they're not lost
                        //      should the session data time out.
                        jsSetCSVValue("input#step2_QuoteCustomer_Ids", response.QuoteCustomer_Ids);
                        
                        // Update the Preview Pane
                        jQuery_AJAXCall_QuoteMakerSummary(false);                    

                        // Clear out Step 1 form 
                        $(':input', $("#step1_Customers"))
                            .not(':button, :submit, :reset')
                            .val('')
                            .removeAttr('checked')
                            .removeAttr('selected');
                            
                        // Scroll page to top
                        $('html').animate({scrollTop:0}, 'fast');
                        
                        return true;
                    } else {
                        alert(response.message);
                        return false;
                    }
                }
            },
            "step2_Products" : 
            {
                url : "/ajax/QuoteProducts", 
                dataType : "json",
                success : function(response)
                {
                    if (response.success) 
                    { 
                        // Add response message to Step 2 title
                        //alert(response.message);
                        
                        // Add the Customer details to the Step 2 form, so they're not lost
                        //      should the session data time out.
                        $("input#step3_QuoteCustomer_Ids").val(response.QuoteCustomer_Ids);
                        $("input#step3_QuoteProduct_Ids").val(response.QuoteProduct_Ids);
                        
                        // Update the Preview Pane
                        jQuery_AJAXCall_QuoteMakerSummary(false);                    

                        // Scroll page to top
                        $('html').animate({scrollTop:0}, 'fast');
                        
                        return true;
                    } else {
                        alert(response.message);
                        return false;
                    }
                }
            },
            "step3_QuoteDetails" : 
            {
                url : "/ajax/QuoteDetails", 
                dataType : "html",
                success : function(response)
                {
                    if (response) 
                    { 
                        
                        $("#step4_Confirm").html(response);

                        // Update the Preview Pane
                        jQuery_AJAXCall_QuoteMakerSummary(true);

                        // Hide the file uploader
                        $("#form_FileUpload").fadeOut();
                        
                        return true;
                    } else {
                        return false;
                    }
                }
            }                   
        },                    
        formOptions :{
            beforeSerialize: function(){
                // Scroll page to top
                $('html,body').animate({scrollTop:0}, 'fast');
                        
                // Remove entire form from Step 1 to 3.
                $("#step1_Customers,#step2_Products,#step3_QuoteDetails,#step_buttons,#ajax_QuoteSummary").remove();
                return true;
            },
            success: jQuery_FormMaker_Success
        }
    });
}

function jQuery_FormMaker_Success(responseText, statusText, xhr, $form)  
{
    // Old-school JS. Anything involving .html refused to work.
    document.getElementById('contentArea').innerHTML = responseText;
}

function jQuery_Setup_ProductPick()
{
    $('.button_productPick').click(function() {
       var el_Row = $(this).parent().parent(); // Get the table row container
       var str_QueryString = $(":input", el_Row).serialize();
       var bool_Valid = 1;
       var int_Index = $("select#OrderProductsModel_unit_ct_ratio", el_Row).attr('selectedIndex');
       
       if (int_Index != undefined && int_Index == 0)
       {
           bool_Valid = 0;
           str_Error = "There was a problem adding the product because:\n\n  - Please pick a CT ratio\n";
       }
       
       if (1 == bool_Valid)
       {
           jQuery.ajax({
                type	: "POST",
                cache	: false,
                dataType: "json",
                url	: "/ajax/QuoteProducts",
                data	: str_QueryString +"&submit_product=1",
                success: function(response) {
                    if (response.success) 
                    { 
                        // Add the Customer details to the Step 2 form, so they're not lost
                        //      should the session data time out.
                        jsSetCSVValue("input#step2_QuoteProduct_Ids", response.QuoteProduct_Ids);
                        // Update the Preview Pane
                        jQuery_AJAXCall_QuoteMakerSummary(false);                    
                        return true;
                    } else {
                        alert(response.message);
                        return false;
                    }                
                }
            });  
       } else {
           alert(str_Error);
       }
       
       $(el_Row).addClass("selected");
       
    });
}

function jQuery_QuoteMaker_PopulateCustomer(int_Customer_Id)
{
    if (int_Customer_Id.length > 0)
    {
         jQuery.ajax({
            type	: "GET",
            cache	: false,
            dataType    : "json",
            url		: "/ajax/CustomerDetails",
            data	: "id="+ int_Customer_Id,
            success: function(response) {
                if (response.success) 
                { 
                    // Autofill the Customer Form on Step 1 with the Values
                    $.each(response.customer, function(key, value) {
                        $('#step1_Customers input[name*='+ key+']').val(value);
                    });

                    if (response.quote != null)
                    {
                        // Autofill the Customer Form on Step 1 with the Values
                        $.each(response.quote, function(key, value) {
                            if ($('#step1_Customers input[name*='+ key+']'))
                            {
                                $('#step1_Customers input[name*='+ key+']').val(value);
                            } else if ($('#step1_Customers textarea[name*='+ key+']')) {
                                $('#step1_Customers textarea[name*='+ key+']').val(value);
                            }
                        });
                    }

                    // Clear search box
                    $('input[name=input_quotecustomer_search]').val("");

                    return true;
                } else {
                    alert(response.message);
                    return false;
                }                
            }
        });  
    }
}

function jQuery_Setup_QuoteSummaryScroll()
{
    var $scrollingDiv = $("#ajax_QuoteSummary");
    jQuery(window).scroll(function(){
        var int_Location = $(window).scrollTop();
        $scrollingDiv
            .stop()
            .animate({
                "marginTop": (int_Location) + "px"
            }, "slow" );
    });
}

function jsSetCSVValue(str_Field, str_Value)
{
    var str_OldValue = $(str_Field).val();
    var arr_OldValues = str_OldValue.split(",");
    var bool_DoAdd = true;
    var int_ArrLength = arr_OldValues.length;
    
    // No need to add if it's already been added
    for (var int_Count = 0; int_Count < int_ArrLength; int_Count++) 
    {
        if (arr_OldValues[int_Count] == str_Value)
        {
            bool_DoAdd = false;
        }
    }
    
    if (true == bool_DoAdd)
    {
        if (str_OldValue.length > 0)
           str_Value = str_OldValue +","+ str_Value;
        $(str_Field).val(str_Value);
    }
}

function jQuery_PopUpProduct()
{
    jQuery('a.product_popup').popup({
        width: 680,
        height: 500,
        titlebar: false,
        status: true,
        resizable: false,
        toolbar: false,
        scrollbars: true,
        menubar: false
    });
}

function jQuery_Setup_CallbackButton()
{
    $('#cancel').click(function(){jQuery_Setup_CallbackCancel()});
    $('#button_Callback_Show').click(function(){
        $('.callbackForm').fadeIn('fast');
    });
}

function jQuery_Setup_CallbackCancel()
{
    $('.callbackForm').fadeOut('fast');
}

function jQuery_Search_Setup()
{
    jQuery_Search_Handle("search", "input#input_searchbox", "/ajax/Search", "div#search_results", 1);
    jQuery_Search_Handle("customer", "input#input_customer_search", "/ajax/CustomerSearch", "div#customer_search_results", 0);
    jQuery_Search_Handle("quote", "input#input_quote_search", "/ajax/QuoteSearch", "div#quote_search_results", 0);
}

function jQuery_Search_Handle(str_Timer_Id, str_InputBox, str_URL, str_ResultsContainer, bool_HideOnEmpty)
{
    jQuery(str_InputBox).keyup(function() {
        clearTimeout(jQuery.data(this, "timer_"+str_Timer_Id));
        var ms = 200; //milliseconds
        var val = this.value;
        var wait = setTimeout(function() {
            if (val.length == 0 && bool_HideOnEmpty == 1) {
                // Hide the suggestion box.
                jQuery(str_ResultsContainer).hide();
            } else {
                jQuery(str_InputBox).removeClass("searchBox").addClass("searchLoading");
                jQuery.ajax({
                    type	: "POST",
                    cache	: false,
                    url		: str_URL,
                    data	: "queryString="+ val,
                    success: function(response,status) {
                        if(response.length > 0)
                        {
                            jQuery(str_ResultsContainer).html(response).show();
                            jQuery(str_InputBox).removeClass("searchLoading").addClass("searchBox");
                        } else {
                            jQuery(str_ResultsContainer).hide();
                            jQuery(str_InputBox).removeClass("searchLoading").addClass("searchBox");
                        }
                    }
                });
            }
        }, ms);
        jQuery.data(this, "timer_"+str_Timer_Id, wait);
    });
}

function jQuery_Handle_QuoteUpdatePriceOnChange()
{
    jQuery_Handle_CopyDeliveryCost();
    jQuery_Handle_QuoteUpdateButtonSwap();
    jQuery_Handle_QuoteCompleteButtonSwap();  
    jQuery("form#form_Quote").one('change', 'input[type=text],select', function() {
        clearTimeout(jQuery.data(this, "timer_quote"));
        var ms = 100; //milliseconds
        var val = this.value;
        var wait = setTimeout(function() {
            jQuery.ajax({
                type	: "POST",
                cache	: false,
                url     : "/my/view",
                data	: jQuery("form#form_Quote").serializeArray(),
                success: function(response, status) {
                    jQuery("div#quoteContainer").empty();
                    jQuery("div#quoteContainer")[0].innerHTML = response;
                    jQuery_Handle_QuoteUpdatePriceOnChange();
                   
                }
            });
        }, ms);
        jQuery.data(this, "timer_quote", wait);
    });
}

function jQuery_Handle_CopyDeliveryCost()
{ 
    jQuery("select#OrdersModel_deliverytype_id").on('change', function()
    {
        jQuery("input#OrdersModel_quote_price_delivery").val($("option:selected", this).attr("title"));
    });

    jQuery("select#OrdersModel_vat_id").on('change', function()
    {
        jQuery("input#OrdersModel_quote_price_vat").val($("option:selected", this).attr("value"));
    });
}

function jQuery_Handle_QuoteUpdateButtonSwap()
{
    jQuery("input#OrdersModel_is_quoted").on('click', function()
    {
        if (jQuery(this).is(':checked'))
        {
            jQuery("input#button_UpdateQuote").fadeOut("fast", function() {
                jQuery("div#div_SendQuote").fadeIn("fast");
            });
        } else {
            jQuery("div#div_SendQuote").fadeOut("fast", function() {
                jQuery("input#button_UpdateQuote").fadeIn("fast");
            });
        }
    });
}

function jQuery_Handle_QuoteCompleteButtonSwap()
{
    jQuery("input#OrdersModel_is_complete").on('click', function()
    {
        if (jQuery(this).is(':checked'))
        {
            jQuery("input#button_UpdateComments").fadeOut("fast", function() {
                jQuery("div#div_CloseQuote").fadeIn("fast");
            });
        } else {
            jQuery("div#div_CloseQuote").fadeOut("fast", function() {
                jQuery("input#button_UpdateComments").fadeIn("fast");
            });
        }
    });
}

function jQuery_Basket_Hoverlinks_Setup()
{
    jQuery("ul.basketList li.allow_hover").hover(function() {
        jQuery(this).find(".option_remove").show();
        jQuery(this).addClass("active");
    }, function() {
        jQuery(this).find(".option_remove").hide();
        jQuery(this).removeClass("active");
    });

    /* Hover over a kit, only highlight the first item in the kit for removal */
    jQuery("ul.basketList li.allow_hover_group").hover(function() {
        jQuery(this).find(".option_remove").show();
        obj_ParentUL = jQuery(this).parent();
        jQuery("li",obj_ParentUL).addClass("active");
        jQuery(this).addClass("active");
    }, function() {
        obj_ParentUL = jQuery(this).parent();
        jQuery("li", obj_ParentUL).find(".option_remove").hide();
        jQuery("li", obj_ParentUL).removeClass("active");
    });
}

function jQuery_Thumbnails()
{
    // Setup image swapping for the thumbs
    jQuery('img.default_thumb,img.technical_thumb,img.kit_thumb').each(function(){
        jQuery(this).bind ('click',
            function()
            {
                var str_src = jQuery(this).attr('src');
                var str_title = jQuery(this).attr('alt');
                var str_scaledimage = jQuery(this).attr('longdesc');
                jQuery('#'+ this.className +'_zoom').attr('src', str_src).attr('alt', str_title);
                jQuery('#'+ this.className +'_href').attr('href', str_scaledimage);
                return false;
            }
            );
    });
        
    // Setup the fancybox for zooming in...
    jQuery("a#default_thumb_href,a#technical_thumb_href,a#kit_thumb_href").fancybox({
        'transitionIn'	:	'elastic',
        'transitionOut'	:	'elastic',
        'speedIn'		:	300,
        'speedOut'		:	300
    });
}

// Hovermenu -  Usually, a style for li:hover would work in all but IE6, so instead of having 2 methods, just use the one we use for IE6 for all browsers.
function jQuery_MenuHover_Setup()
{
    jQuery("#nav ul  li[id^='nav_child_']").hover(function() {
        obj_This = this;
        jQuery("#nav ul li[id^='nav_child_']").each(function(int_Index, obj_List)
        {
            if (jQuery(">a", this).hasClass("current") || jQuery(">a", this).hasClass("active"))
            {
                if (jQuery(">a", this).hasClass("current"))
                    jQuery(this).removeClass("current");
                jQuery(">a", this).removeClass("active");
                jQuery(">ul", this).removeClass("active");
            }
        });
        jQuery(">ul", this).addClass("active");
        jQuery(">a", this).addClass("active");
    }, function() {
        obj_This = this;
        jQuery("#nav ul li[id^='nav_child_']").each(function(int_Index, obj_List)
        {
            if (jQuery(">a", this).hasClass("active") && obj_This.id != this.id)
            {
                jQuery(">a", this).removeClass("active");
                jQuery(">ul", this).removeClass("active");
            }
        });
    });	
} 

// Used on the Product page to swap between	Technical Information / FAQ / Downloads
function jQuery_SwitchList_Setup()
{
    jQuery("div.switchlist").each(function(int_Index, obj_List)
    {
        // Hide all items in the list
        jQuery("ul.switchlist_data>li", obj_List).hide();
		
        // Show the first item
        jQuery("ul.switchlist_data>li:first-child", obj_List).show();
		
        // Add the active class to the first menu item
        jQuery("ul.switchlist_menu>li:first-child a").addClass("active");
		
        // Add the click event to each menu item
        jQuery("ul.switchlist_menu>li a").click(function() {
            jQuery_SwitchList_Swap(this, obj_List);
            return false;
        });
    });
}

function jQuery_SwitchList_Swap(obj_ItemPicked, obj_List)
{
    // Find current index
    int_IndexPicked = jQuery("ul.switchlist_menu li a", obj_List).index(obj_ItemPicked);
	
    // Clear all styling and highlight current.
    jQuery("ul.switchlist_menu li a", obj_List).removeClass("active");
    jQuery(obj_ItemPicked).addClass("active");

    // Hide all elements
    jQuery("ul.switchlist_data>li", obj_List).hide();
	
    // Show chosen element based on index
    jQuery("ul.switchlist_data>li:nth-child("+ (int_IndexPicked + 1) +")", obj_List).show();
	
    return false;
}

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

function jQuery_AJAXCall(str_FormName, str_URL, str_ResultContainer, str_ButtonName, str_Data)
{
    jQuery(str_FormName).bind("submit", function() {
        jQuery.ajax({
            type	: "POST",
            cache	: false,
            url		: str_URL,
            data	: jQuery(this).serializeArray(),
            success: function(response, status) {

                jQuery(str_ResultContainer).fadeOut("fast", function() 
                {
                    
                    jQuery(str_ResultContainer).html(response);
                    jQuery(str_ResultContainer).fadeIn("fast");
                });
            }
        });
        return false;
    });
}

function jQuery_AJAXCall_FancyBox(str_FormName, str_Action, str_URL)
{
    jQuery(str_FormName).bind(str_Action, function() {
        jQuery.fancybox.showActivity();
        jQuery.ajax({
            type	: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            cache	: false,
            url		: str_URL,
            data	: jQuery(this).serializeArray(),
            success: function(data, status) {
                jQuery.fancybox(data, arr_FancyBoxSettings);
            }
        });
        return false;
    });
}

function jQuery_AJAXCall_BasketView_FancyBox()
{
    jQuery.fancybox.showActivity();
    jQuery.ajax({
        type		: "GET",
        contentType	: "application/x-www-form-urlencoded; charset=utf-8",
        dataType	: "html",
        cache		: false,
        url			: "/ajax/BasketAddView",
        success: function(data, status) {
            jQuery.fancybox(data, arr_FancyBoxSettings);
        }
    });
}

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

// Callback request handler
function jQuery_AJAXCall_Callback()
{
    str_FormName 		= "form#form_Callback";
    str_URL 			= "/ajax/callback";
    str_ResultContainer = "div#ajax_CallbackContainer";
    str_ButtonName		= "button#button_Callback";
    jQuery_AJAXCall(str_FormName, str_URL, str_ResultContainer, str_ButtonName, null);
}

function jQuery_AJAXCalls_BindAll()
{
    jQuery_AJAXCall_FancyBox("form#form_BasketAddItem,form#form_BasketAddKit", "click", "/ajax/BasketAddView");
}

function jQuery_AJAXCall_BasketView()
{
    jQuery("#button_BasketView").bind("click", function() {
        jQuery_AJAXCall_BasketView_FancyBox();
        return false;
    });
}

function jQuery_AJAXCall_ContinueRegister()
{
    jQuery_AJAXCall_FancyBox("a#href_register", "click", "/register");
}

function jQuery_AJAXCall_DoLogin()
{
    jQuery_AJAXCall_FancyBox("form#form_LoginPopup", "submit", "/ajax/Login");
}

function jQuery_AJAXCall_DoRegister()
{
    jQuery_AJAXCall_FancyBox("form#form_RegisterPopup", "submit", "/register");
}

function jQuery_AJAXCall_QuoteMakerSummary(bool_HideDelete)
{
    bool_HideDelete = (bool_HideDelete) ? 1 : 0;
    
    str_URL = "/ajax/QuoteSummary?hd="+ bool_HideDelete;
    str_ResultContainer = "div#ajax_QuoteSummary";
    jQuery.ajax({
        type	: "GET",
        cache	: false,
        url	: str_URL,
        success : function(response,status) {
            jQuery(str_ResultContainer).fadeOut("fast", function()
            {
                jQuery(str_ResultContainer).html(response);
                jQuery(str_ResultContainer).fadeIn("fast");
            });
        }
    });
}


function jQuery_AJAXCall_QuoteMaker_AddDocument(int_File_Id)
{
    str_URL = "/ajax/QuoteFilePick/"+ int_File_Id;
    jQuery.ajax({
        type	: "GET",
        cache	: false,
        url	: str_URL,
        success : function(response,status) {
            jQuery_AJAXCall_QuoteMakerSummary(false);
        }
    });
}


function jQuery_AJAXCall_BasketShortcut()
{
    str_URL 		= "/ajax/BasketShortcutView";
    str_ResultContainer = "div#ajax_BasketContainer";
    jQuery.ajax({
        type	: "GET",
        cache	: false,
        url		: str_URL,
        success : function(response,status) {
            jQuery(str_ResultContainer).fadeOut("fast", function()
            {
                jQuery(str_ResultContainer).html(response);
                jQuery(str_ResultContainer).fadeIn("fast");
            });
        }
    });
}

function jQuery_AJAX_RefreshBasket()
{	
    jQuery.ajax({
        type	: "POST",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "html",
        cache	: false,
        url		: "/ajax/BasketUpdateView",
        data	: jQuery("form#form_BasketList").serializeArray(),
        success: function(data, status) {
            //jQuery.fancybox(data, arr_FancyBoxSettings);
            jQuery("div#fancybox-inner").html(data);
            jQuery.fancybox.resize();
        }
    });
}

function jQuery_AJAXCall_RefreshQuote()
{
    // Basket Update View - Updating Quantity
    jQuery("button#button_BasketRefresh").bind("click", function() {
        jQuery_AJAX_RefreshBasket();
    });
}

function jQuery_AJAXCall_ContinueBrowsing()
{
    // Basket Update View - Continue Browsing
    jQuery("button#button_Continue").bind("click", function() {
        jQuery.fancybox.close();
    });
}

function jQuery_AJAXCall_SubmitBasket_RefreshBasketLink()
{
    jQuery.fancybox.showActivity();
    jQuery.ajax({
        type	: "POST",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "html",
        cache	: false,
        url		: "/ajax/BasketUpdateView",
        data	: jQuery("form#form_BasketList").serializeArray(),
        success: function(data, status) {
            jQuery.fancybox.hideActivity();
            jQuery_AJAXCall_BasketShortcut();
        }
    });
}

function jQuery_AJAXCall_ContinueLogin()
{
    jQuery("button#button_RequestQuote").bind("click", function() {
        jQuery.fancybox.showActivity();
        jQuery.ajax({
            type	: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            cache	: false,
            url		: "/ajax/Login",
            data	: jQuery("form#form_BasketList").serializeArray(),
            success: function(data, status) {
                jQuery.fancybox(data, arr_FancyBoxSettings);
                jQuery("button#button_RequestQuote,button#button_Continue").removeClass("disabled");
            }
        });
        return false;
    });
}


function jQuery_AJAXCall_UpdateCTRatio()
{
    jQuery("select.form_select_ct_ratio").bind("change", function() {
        bool_DoCall = jQuery_Basket_CheckButtons();
        if (bool_DoCall == true)
        {
            jQuery.fancybox.showActivity();
            jQuery.ajax({
                type	: "POST",
                cache	: false,
                url		: "/ajax/BasketUpdateView",
                data	: jQuery("form#form_BasketList").serializeArray(),
                success: function(data, status) {
                    //jQuery.fancybox(data, arr_FancyBoxSettings);
                    jQuery.fancybox.hideActivity();
                    jQuery("div#fancybox-inner").html(data);
                    jQuery("button#button_RequestQuote,button#button_Continue").removeClass("disabled");
                    jQuery.fancybox.resize();
                }
            });
        }
        return false;
    });
}

function jQuery_Basket_CheckButtons()
{
    bool_DoButtonSwap = true;
    jQuery("button#button_RequestQuote").removeClass("disabled");
    jQuery_AJAXCall_ContinueBrowsing();
		
    int_TallyCount = 0;
    // Check all the CTs have been set...
    jQuery("select.form_select_ct_ratio").each(function(i,o) {
        int_TallyCount++;
        if (o.value == "")
            bool_DoButtonSwap = false;
    });

    if (bool_DoButtonSwap == true)
    {
        jQuery_AJAXCall_ContinueLogin();
    } else if (jQuery("input#basket_tally").val() > 0) {
        //jQuery("button#button_RequestQuote,button#button_Continue").addClass("disabled").unbind("click");
		
        jQuery("button#button_RequestQuote").addClass("disabled").unbind("click");
        jQuery("div#basketNote").fadeIn(500, function() {
            jQuery("div#basketNote").slideDown(500);
            jQuery.fancybox.resize();
        });
    }
	
    // If there are no tallys and nothing in the basket, we need to allow this...
    if (jQuery("input#basket_tally").val() == 0)
    {
        jQuery("button#button_RequestQuote").addClass("disabled").unbind("click");
    }
	
    return bool_DoButtonSwap;
}

function jQuery_BindClose()
{
    // Any button with a class of button close will the fancy box
    jQuery(".button_Close").bind("click", function() {
        jQuery.fancybox.close();
        jQuery_AJAXCall_BasketShortcut();
    });
}

// Delete item option - it updates the quantity & reloads the form
function jQuery_BindDelete()
{
    jQuery(".option_delete").bind("click", function() {
        jQuery("input[id^='form_quantity_']",jQuery(this).parent()).val(0);
        jQuery_AJAX_RefreshBasket();
    });
}




////////////////////////////////////////////////////////////////////////////////

// File Upload

function jQuery_FileUpload_Complete(responseJSON)
{
    if (responseJSON["error"] != null)
    {
        jQuery_FileUpload_Fail(responseJSON["error"]);
    } else {
        $('#form_FileUpload_Error').addClass('hidden');
        jQuery_AJAXCall_QuoteMakerSummary(false);
    }
}

function jQuery_FileUpload_Fail(str_Message)
{
    $('#form_FileUpload_Error').removeClass('hidden');
    $('#form_FileUpload_Error').html(str_Message);
}
