/* Author: Ben Hutchings

 */

jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) {
  if (this.is(":hidden")) {
    return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
  } else {
    return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback);
  }
};

$(window).load(function(){

    // Fade stuff
    $(".faded").each(function(i) {
        //$(this).delay(i * 300).fadeIn();
        $(this).fadeIn();
    });


    $("a.fadeout").click(function(e){
        e.preventDefault();
        /*var loc = this.href;
        var amount = $($(".faded").get().reverse()).each(function(i) {
            $(this).delay(i * 300).fadeOut(function () {if (i == amount -1) {window.location = loc;}});
        }).length;*/
        var loc = this.href;
        var amount = $($(".faded").get().reverse()).each(function(i) {
            $(this).fadeOut(function () {
                if (i == amount -1) {
                    window.location = loc;
                }
            });
        }).length;
    });

    //Pseudo onclicks
    $("#main-home-bl").click(function(){
        window.location = "register";
    });

    // Forms etc
    $(".home-login-pass, #ad_pass").focus(function(){
        if(this.value == this.defaultValue){
            this.value = '';
            this.type = 'password';
        }
        this.select();

    });
    $(".home-login-pass, #ad_pass").blur(function(){
        if(this.value == ''){
            this.type = 'text';
            this.value = this.defaultValue;
        }
    });
    $("input[type=password].blank,input[type=email].blank,textarea.blank").blur(function(){
        if(this.value == ''){
            this.value = this.defaultValue;
        }
    });
    $("input[type=text].blank,input[type=email].blank,textarea.blank").focus(function(){
        this.select();
    });
    $("input[type=text].blank,input[type=email].blank,textarea.blank,input[type=password].blank,.home-login-pass,#ad_pass").mouseup(function(e){
        e.preventDefault();
    });
    $("input[type=text].blank,input[type=email].blank,textarea.blank").blur(function(){
        if(this.value == ''){
            this.value = this.defaultValue;
        }
    });
    $.tools.validator.fn("[data-default]", "Please fill in this form", function(input, value) {
        var def = input.attr("data-default");
        return (value!=def);
    });
    $("#tradeForm").validator({
        offset: [24, 0],
        position: 'center left'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {
            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "login",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax login', this, arguments);
                    if (html=="0") {
                        alert("Your Username and Password combination is incorrect");
                    } else if (html=="2") {
                        alert("Your account is pending activation\nPlease wait for your activation email");
                    } else {
                        //alert("Username or Pass OK");
                        window.location = 'cards.php';
                    }
                },
                error: function (err) {
                    log('inside ajax login', this, arguments);
                }
            });

            e.preventDefault();
        }
    });
    if($('#cards_filter').length){
        $("#cards_filter select").change(function(e) {

            var form = $(this);
            var serdata = form.serialize();
            var field_name = $(this).attr("name");
            var field_value = $(this).val();
            //Reset the selectors and keep the one that triggered filter
            $('#cards_filter').find('select').val(function(index,value){
                if($(this).attr("name") == field_name){
                    return field_value;
                }else{
                    return "-1";
                }
            });
            $.ajax({
                type: "POST",
                url: "filtered_cards",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('filtering cards', this, arguments);
                    $('#card_list').fadeOut(400,function(){
                        if (html=="0") {
                            alert("An error occurred retrieving data");
                        } else {
                            $('#card_list').html(html);
                        }
                        $('#card_list').fadeIn();
                        // Refresh Tooltips
                        setTooltips();
                        //Bind colorbox to images
                        bind_colorbox_listener();
                    });
                },
                error: function (err) {
                    log('filtering cards', this, arguments);
                }
            });
            return false;
        });
    }

    //Ajax Pagination click
    $(".pagination a").live('click', function(e) {

        var page = $(this).text();
        if(page.substring(page.toLowerCase().indexOf('last', 0)).length > 0){
            //Page is last so get page number.
            page = $(this).attr('href').substring($(this).attr('href').toLowerCase().indexOf('p=', 0)+2);
        }
        $.ajax({
            type: "POST",
            url: "filtered_cards",
            data: "p="+page,
            cache: false,
            success: function (html) {
                log('filtering cards(pagination)', this, arguments);
                $('#card_list').fadeOut(400,function(){
                    if (html=="0") {
                        alert("An error occurred retrieving data");
                    } else {
                        $('#card_list').html(html);
                    }
                    $('#card_list').fadeIn();
                    // Refresh Tooltips
                    setTooltips();
                    //Bind colorbox to images
                    bind_colorbox_listener();
                });
            },
            error: function (err) {
                log('filtering cards(pagination)', this, arguments);
            }
        });
        return false;
    });
    $("#contact_form").validator({
        offset: [0, 354],
        position: 'center left',
        messageClass: 'conerror'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {

            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "sendenquiry",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax contact', this, arguments);
                    $('#contact_form').fadeOut(400,function(){
                        if (html=="0") {
                            alert("An error occurred");
                        } else {
                            $('#contact_form').html('<p>Thank you for your enquiry. We will be in touch soon.</p>');
                        }
                        $('#contact_form').fadeIn();
                    });
                },
                error: function (err) {
                    log('inside ajax login', this, arguments);
                }
            });

            e.preventDefault();
        }
    });
    
    
    $("#agent_form").validator({
        offset: [0, 176],
        position: 'center left',
        messageClass: 'ageerror'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {
            var form = $(this);
            var serdata = form.serialize();
            /*alert(serdata);*/
            $.ajax({
                type: "POST",
                url: "getagents",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax getagents', this, arguments);
                    $('#agent-results').fadeOut(400,function(){
                        if (html=="0") {
                            alert("An error getagents");
                        } else {
                            $('#agent-results').html(html);
                        }
                        $('#agent-results').fadeIn();
                    });
                },
                error: function (err) {
                    log('inside ajax login', this, arguments);
                }
            });

            e.preventDefault();
        }
    });
    

    /*$("#artist_form").validator({
    offset: [0, 354],
    position: 'center left',
    messageClass: 'arterror'
}).submit(function(e) {
    if (!e.isDefaultPrevented()) {
        
        $('#file_upload').uploadifyUpload();

        var form = $(this);
        var serdata = form.serialize();
        $.ajax({
            type: "POST",
            url: "sendartist",
            data: serdata,
            cache: false,
            success: function (html) {
                log('inside ajax artist', this, arguments);
                if (html=="0") {
                    alert("An error occurred");
                } else {
                    alert("Form sent ok");
                }
            },
            error: function (err) {
                log('inside ajax artist', this, arguments);
            }
        });

        e.preventDefault();
    }
});*/

    if($("img.i").length){
        setTooltips();
    }

    if($(".card_thumb").length){
        bind_colorbox_listener();
    }

    //Slider
    $('#slider').nivoSlider({
        effect: 'fade',
        controlNav: false,
        directionNav: false
    });

    //Cart Buttons
    $(".add").live('click', function() {
        var card = $(this).parent().find('.qtymeta .cardid').val();
        var quantity = $(this).parent().find('.qtymeta .qty').val();
        var field = $(this).parent().find('.qtymeta .qty');
        var button = $(this);

        //Validate quantity first
        if(isNaN(quantity)){
            alert("Please enter a valid quantity.");
            setTimeout(function(){
                field.focus();
            },0);
            return false;
        }

        $.ajax({
            type: "POST",
            url: "addtocart",
            data: "card="+card+"&quantity="+quantity,
            cache: false,
            success: function (html) {
                log('inside ajax addtocart', this, arguments);
                button.fadeOut("slow",function(){
                    button.css('background-color', '#9d2429').text("Add More").fadeIn();
                });
            },
            error: function (err) {
                log('inside ajax addtocart', this, arguments);
                button.fadeOut("slow",function(){
                    button.css('color', '#9d2429').text("Error!").fadeIn();
                });
            }
        });
    });

    //Remove row from cart
    $("img.remove_row").live('click', function(e) {

        var card = $(this).attr("name");
        $.ajax({
            type: "POST",
            url: "removefromcart",
            data: "name="+card,
            cache: false,
            success: function (html) {
                log('removing row', this, arguments);
                $('#basket').fadeOut(400,function(){
                    if (html=="0") {
                        alert("An error occurred retrieving data");
                    } else {
                        $('#basket').html(html);
                    }
                    $('#basket').fadeIn();
                });
            },
            error: function (err) {
                log('removing row', this, arguments);
            }
        });
        return false;
    });

    //Update cart form validator bind call.
    form_listener();

    $("#registration_form").validator({
        offset: [0, 0],
        position: 'bottom left',
        messageClass: 'regerror'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {
            $('#registration_form .sub-btn').attr("disabled", "true").css("color","#797979");
            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "registertrader",
                data: serdata,
                cache: false,
                success: function (html) {
                    $('#selector').fadeOut(400,function(){
                        if (html=="0") {
                            $('#selector').html('<div id="blurb"><h1>Registration Failed</h1><p>There was a problem with your registration. Please contact us using the link in the menu.</p></div>');
                        } else {
                            $('#selector').html('<div id="blurb"><h1>Registration Success</h1><p>Thank you for registering for a Milkwood Trade account. You will receive an email on your registered email address once your account has been created.</p></div>');
                        }
                        $('#selector').fadeIn();
                    });
                    log('inside ajax registertrader', this, arguments);
                },
                error: function (err) {
                    log('inside ajax registertrader', this, arguments);
                }
            });
            e.preventDefault();
        }
    });

    $("#updatetrader_form").validator({
        offset: [0, 0],
        position: 'bottom left',
        messageClass: 'regerror'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {
            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "updatetrader",
                data: serdata,
                cache: false,
                success: function (html) {
                    $('.sub-btn').fadeOut(400,function(){
                        if (html=="0") {
                            $('.sub-btn').val('UPDATE TRADER - NO CHANGE').fadeIn();
                        } else {
                            $('.sub-btn').val('UPDATE SUCCEEDED').fadeIn();
                        }
                    });
                    log('inside ajax updatetrader', this, arguments);
                },
                error: function (err) {
                    log('inside ajax updatetrader', this, arguments);
                }
            });
            e.preventDefault();
        }
    });
    
    $("#updateproduct_form").validator({
        offset: [0, 0],
        position: 'bottom left',
        messageClass: 'regerror'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {
            //$('#updateproduct_form .sub-btn').attr("disabled", "true").css("color","#797979");
            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "../inc/updateproduct.php",
                data: serdata,
                cache: false,
                success: function (html) {
                    $('.sub-btn').fadeOut(400,function(){
                        if (html=="0") {
                            $('.sub-btn').val('UPDATE PRODUCT - NO CHANGE').fadeIn();
                        } else {
                            $('.sub-btn').val('UPDATE SUCCEEDED').fadeIn();
                        }
                    });
                    log('inside ajax updateproduct', this, arguments);
                },
                error: function (err) {
                    log('inside ajax updateproduct', this, arguments);
                }
            });
            e.preventDefault();
        }
    });

    $("#complete_order_butt").click(function(e){
        if (!e.isDefaultPrevented()) {
            $('#complete_order_butt').css("color","#797979");
            $.ajax({
                type: "POST",
                url: "completeorder",
                //data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax completeorder', this, arguments);
                    $('#selector').fadeOut(400,function(){
                        if (html=="0") {
                            alert("An error occurred");
                        } else {
                            $('#selector').html('<p>Thank you for your order.</p><p>A confirmation email has been sent to the invoice email address you provided.</p>');
                        }
                        $('#selector').fadeIn();
                    });
                },
                error: function (err) {
                    log('inside ajax completeorder', this, arguments);
                }
            });
        }
        e.preventDefault();
    });

    // Copy details from invoice to delivery address fields
    $('#same_as_invoice').click(function(){
        if($(this).attr('checked')){
            //Copy details in
            $('#t_del_name').val($('#t_inv_name').val());
            $('#t_del_company').val($('#t_inv_company').val());
            $('#t_del_address').val($('#t_inv_address').val());
            $('#t_del_town').val($('#t_inv_town').val());
            $('#t_del_county').val($('#t_inv_county').val());
            $('#t_del_postcode').val($('#t_inv_postcode').val());
        }else{
            //Clear details
            $('#t_del_name').val($('#t_del_name').attr('data-default'));
            $('#t_del_company').val($('#t_del_company').attr('data-default'));
            $('#t_del_address').val($('#t_del_address').attr('data-default'));
            $('#t_del_town').val($('#t_del_town').attr('data-default'));
            $('#t_del_county').val($('#t_del_county').attr('data-default'));
            $('#t_del_postcode').val($('#t_del_postcode').attr('data-default'));
        }
    });

    $("input#t_user_name").live('keyup', function(e) {
        log('in usernamecheck', this, arguments);
        var username = $('#t_user_name').val();
        if (1>username.length) {
            $('.usernamecheck').css('color', '#b0a9a9').val("Enter a username to begin checking...");
            return true;
        } else if(username.length<4) {
            $('.usernamecheck').css('color', '#ff4444').val("Username too short, please enter 4 characters or more");
            return true;
        }
        $.ajax({
            type: "POST",
            url: "usernamecheck",
            data: "username="+username,
            cache: false,
            success: function (html) {
                log('usernamecheck success', this, arguments);
                if (html=="0") {
                    $('.usernamecheck').css('color', '#44ff44').val("Username is ok");
                }
                else {
                    $('.usernamecheck').css('color', '#ff4444').val("That username is taken, please choose another one");
                }
            },
            error: function (err) {
                log('usernamecheck error', this, arguments);
            }
        });
        return true;
    });

    $("input#t_cont_name").live('keyup', function(e) {
        $("input#t_inv_name").val($(this).val());
        $("input#t_del_name").val($(this).val());
    });
    $("input#t_comp_name").live('keyup', function(e) {
        $("input#t_inv_company").val($(this).val());
        $("input#t_del_company").val($(this).val());
    });

    $(".in-thing-list").click(function(event) {
        event.preventDefault();
        var outthing = $(this).parent().parent();
        var inthing = $(this).parent();
        var inthingheight = inthing.css('height');
        if (outthing.css('height')>'1em') {
            outthing.animate( {
                height:'1em'
            }, 500 );
        } else {
            outthing.animate( {
                height: inthingheight
            }, 500 );
        }
    });

    $(".in-thing-reorder").click(function(event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "inc/recreatecart.php",
            data: "orderid="+$(this).attr("data-orderid"),
            cache: false,
            success: function (html) {
                log('recreatecart success', this, arguments);
                if (html=="0") {

                } else {
                    window.location = "cart";
                }
            },
            error: function (err) {
                log('recreatecart error', this, arguments);
            }
        });

    });

    $("a.status-lights").click(function(e){
        e.preventDefault();
        var status = 0;
        var oldc = "state2";
        var newc = "state2";
        var id = $(this).attr("data-id");
        var href = $(this).attr("href");
        //alert(href);
        var benj = $(this);

        if ($(this).hasClass("state1")) { // Active to Disabled
            status = 2;
            oldc = "state1";
            newc = "state2";
        } else if($(this).hasClass("state2")) { // Disabled to Active
            status = 1;
            oldc = "state2";
            newc = "state1";
        } else if($(this).hasClass("state0")) { // Pending to Live
            status = 1;
            oldc = "state0";
            newc = "state1";
        }

        $.ajax({
            type: "POST",
            //url: "../inc/setstatus.php",
            url: "../inc/"+href,
            data: "status="+status+"&id="+id+"&oldc="+oldc+"&newc="+newc,
            cache: false,
            success: function (html) {
                log('setstatus success', this, arguments);
                if (html=="1") {
                    benj.fadeOut(400,function(){
                        benj.removeClass(oldc).addClass(newc).fadeIn();
                    });
                } else {
                    alert("Ah.. status setting failed, Call Fluid2!");
                }
            },
            error: function (err) {
                log('setstatus error', this, arguments);
            }
        });

    });

    $(".hidden_rows").hide();

    $(".do-thing").click(function (e) {
        e.preventDefault();
        $(this).closest('tbody').next().slideToggle("fast");
    });
    
    $(".delete-product").click(function (e) {
        e.preventDefault();
        $(this).closest('td').children('.del-sure').animate({opacity: 'toggle'}, 800);
    });
    
    $(".del-sure").click(function (e) {
        e.preventDefault();
            var pid = $(this).attr("data-pid");
            var tbody = $(this).closest('tbody');

            $.ajax({
                type: "POST",
                url: "../inc/deleteproduct.php",
                data: "pid="+pid,
                cache: false,
                success: function (html) {
                    log('inside ajax deleteproduct', this, arguments);
                    tbody.fadeThenSlideToggle('fast');
                },
                error: function (err) {
                    log('inside ajax deleteproduct', this, arguments);
                }
            });
        //}
    });
    
    
    $(".resend-order").click(function(e){
        e.preventDefault();
        //if(confirm("Hang on... Are you SURE you want to resend the Order Confirmation email to the Trader?")){
            $(this).fadeOut(400,function(){
                $(this).html("Feature not activated yet...").fadeIn();  
            });
        //};
    });


    $("#artist_form").validator({
        offset: [0, 354],
        position: 'center left',
        messageClass: 'arterror'
    }).submit(function(e) {

        if (!e.isDefaultPrevented()) {
        
            $('#file_upload').uploadifyUpload();

            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "sendartist",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax artist', this, arguments);
                    
                    $('#fade-holder').fadeOut(400,function(){
                        if (html=="0") {
                            log('error with sending artist :(', this, arguments);
                            $('#fade-holder').html("<h2>Thank You!</h2>We will be in touch shortly.");
                        } else {
                            $('#fade-holder').html("<h2>Thank You!</h2>We will be in touch shortly.");
                        }
                        $('#fade-holder').fadeIn();
                    });
                },
                error: function (err) {
                    log('inside ajax artist', this, arguments);
                }
            });

            e.preventDefault();
        }

        e.preventDefault();
        $('#file_upload').uploadifyUpload();
    });


    $('#file_upload').uploadify({
        'uploader'  : '/uploadify/uploadify.swf',
        'script'    : '/uploadify/uploadify.php',
        'cancelImg' : '/uploadify/cancel.png',
        'folder'    : '/uploads',
        'multi'          : true,
        'fileExt'        : '*.jpg;*.gif;*.png;*.png',
        'fileDesc'       : 'Image Files (.JPG, .GIF, .PNG)',
        'queueID'        : 'custom-queue',
        'queueSizeLimit' : 3,
        'simUploadLimit' : 3,
        'scriptData'  : {'upload_key':$('#upload_key').val()},
        'buttonImg': 'img/select-images.png',
        'width': '351',
        'height': '32',
        'removeCompleted': false,
        'onSelectOnce'   : function(event,data) {
            log('onSelectOnce', this, arguments);
            $('#status-message').html(data.fileCount + ' files queued for upload...<br />');
            $('#upload-image').animate({
                opacity: 1
            }, 1000, 'linear').css('cursor', 'pointer');
        },
        'onComplete'  : function(event, ID, fileObj, response, data) {
            log('onComplete', this, arguments);
            if (data.fileCount == 0) {
                $('#upload-image').animate({
                    opacity: 0.3
                }, 1000, 'linear').css('cursor', 'default');
            }
        },
        'onAllComplete'  : function(event,data) {
            log('onAllComplete', this, arguments);
            $('#status-message').fadeOut(function(){
                $('#status-message').html("Thank you! " + data.filesUploaded + ' files were succesfully uploaded.').fadeIn();
            });
        },
        'onCancel'  : function(event,ID,fileObj,data) {
            log('onCancel', this, arguments);
            if (data.fileCount == 0) {
                $('#upload-image').animate({
                    opacity: 0.3
                }, 1000, 'linear').css('cursor', 'default');
                $('#status-message').fadeOut(function(){
                    $('#status-message').html("We would like to see some of your work. Please 'Select' up to three images then use the 'Upload Your Images' button.").fadeIn();
                });
            }
        }
    });
    
    $('#upload-image').click(function(e) {
        $('#file_upload').uploadifyUpload();
    });


});








// Tooltips
function setTooltips(){
    $("img.i").each(function(){
        $(this).tooltip({
            offset: [-18, 3],
            opacity: 1,
            position: 'bottom right',
            effect: 'fade',
            relative: true
        });
    });
}

function bind_colorbox_listener(){
    $('.card_thumb').lightBox({
        fixedNavigation:true,
        overlayBgColor:'#fff',
        imageLoading: '/img/lb/lightbox-ico-loading.gif',
	imageBtnClose: '/img/lb/lightbox-btn-close.gif',
	imageBtnPrev: '/img/lb/lightbox-btn-prev.gif',
	imageBtnNext: '/img/lb/lightbox-btn-next.gif'
    });
}

//Update cart
//Normal .validator wont rebind on the ajax reload
//so creating as a function so it can be called
//after the reload.
form_listener = function(){
    $("#basket_form").validator({
        offset: [0, 50],
        position: 'center left'
    }).submit(function(e) {
        if (!e.isDefaultPrevented()) {

            var form = $(this);
            var serdata = form.serialize();
            $.ajax({
                type: "POST",
                url: "updatecart",
                data: serdata,
                cache: false,
                success: function (html) {
                    log('inside ajax updatecart', this, arguments);
                    $('#basket').fadeOut(400,function(){
                        if (html=="0") {
                            alert("An error occurred retrieving data");
                        } else {
                            $('#basket').html(html);
                        }
                        $('#basket').fadeIn();
                        form_listener();
                    });
                },
                error: function (err) {
                    log('inside ajax updatecart', this, arguments);
                }
            });

            e.preventDefault();
        }
    });
}

