// Some global variables for zooming
var zooming = false
var zoom_area, zoom_preload, zoom_screen, zoom_lens, zoom_large_image, zoom_thumb, zoom_img_src, zoom_source, zoom_source_width, zoom_source_height, zoom_icon, zoom_shadow;
var mouse_x = mouse_y = 0;
var zoom_lens_w = zoom_lens_h = 0;
var w_factor = h_factor = 1;
var lens_x = lens_y = 0;
var main_zoom_x = main_zoom_y = 0;
var zoom_initialised = false;

$(document).ready(function() {
        
    // Some variables for zooming
    zoom_area = $("#zoom_area");
    zoom_preload = $("#zoom_preload");
    zooming = false;
    zoom_screen = $("#zoom_screen");
    zoom_lens = $("#zoom_lens");
    zoom_shadow = $("#zoom_shadow");
    zoom_large_image = $("#zoom_img");
    zoom_lens_w = zoom_lens_h = 0;
    w_factor = h_factor = 1;
    
    // Activate mouse following
    $(document)
        .bind("mousemove", function(e)
        {
            if(zooming == true){
                mouse_x = e.pageX - zoom_screen.offset().left;
                mouse_y = e.pageY - zoom_screen.offset().top;
                toiDoZoom(e);
            }
        });
    
    /**
     * Image zoom functionality
     */
    $("a.zoomer")
        .click(function(e){
            
            if(zooming == false){
                
                // Set zooming to true
                zooming = true;
                
                // Show waiting cursor
                $("body")
                    .css("cursor", "progress");
                
                // Some variables to cache
                zoom_thumb = $(this);
                zoom_icon = $(this).find("em");
                zoom_img_src = $(this).attr('href');
                mouse_x = mouse_y = 0;
                zoom_source = $(this).find("img");
                zoom_source_width = zoom_source.width();
                zoom_source_height = zoom_source.height();
                
                // Initialise zoom screen
                zoom_screen
                    .css("height", zoom_source_height + "px")
                    .css("width", zoom_source_width + "px")
                    .fadeTo(0, 0.00)
                    .show()
                    .fadeTo("normal", 0.60);
                
                // Add correct image to zoom lens
                zoom_lens
                    .find("img")
                    .attr("src", zoom_source.attr("src"))
                    .css("position", "absolute")
                    .hide()
                    .fadeIn();

                // Hide zoom icon
                zoom_icon
                    .fadeOut();
                
                // Show preloader
                zoom_preload
                    .show();
                
                // Show zoom area
                zoom_area
                    .show();
                    
                // Show shadow
                zoom_shadow
                    .show();
                
                // Add image and make sure it's hidden
                zoom_large_image
                    .hide()
                    .attr("src", zoom_img_src);
                
                // Remove previous load
                zoom_large_image.get(0).onload = function(){};
                                
                // Add load function for the image
                zoom_large_image
                    .load(function(){
                        
                        // Show moving cursor
                        $("body")
                            .css("cursor", "move");
                        
                        // Get zoom factor
                        w_factor = zoom_thumb.width() / zoom_large_image.width();
                        h_factor = zoom_thumb.height() / zoom_large_image.height();
                        
                        // Initialise zoom lens
                        zoom_lens_w = Math.round(zoom_area.width() * w_factor);
                        zoom_lens_h = Math.round(zoom_area.height() * h_factor);
                        zoom_lens
                            .height(zoom_lens_h)
                            .width(zoom_lens_w)
                            .fadeIn();
                        
                        // Move lens and main image to initial position
                        if(zoom_initialised == false){
                            mouse_x = e.pageX - zoom_screen.offset().left;
                            mouse_y = e.pageY - zoom_screen.offset().top;
                        }
                        toiMoveLens();
                        toiMoveMainImage();
                        
                        // Hide preloader
                        zoom_preload
                            .hide();
                        
                        // Fade in image
                        $(this)
                            .fadeIn();
                        
                    });
                
            }
            
            // Don't do the default document on click when clicking on the image
            return false;
                    
        });
    
    
    /**
     * Stop the zooming
     */
    $(document)
        .click(function(){
            toiStopZoom();
        });
    
    /**
     * Thumbnail clicks
     */
    $(".product_thumb_wrap a")
        .click(function(){
            
            toiStopZoom();
            
            var clicked_photo_id = $(this).attr("id");
            // Show corresponding large image
            $("#product_main_image div")
                .each(function(){
                    if($(this).hasClass("product_main_image_" + clicked_photo_id)){
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            return false;
        });
    
    // Unavailable products (I think...)
    $("a[id^='unavailable']").click(function() {
        var title = $(this).attr("title");
        showError(title);
    });  
    
});


/* Main zoom function */
function toiDoZoom(e)
{
    
    if(zooming == true){
        
        zoom_initialised = true;
        
        // Move lens
        toiMoveLens();
        
        // Move main image
        toiMoveMainImage();
        
    }
    
}

function toiStopZoom()
{
    
    if(zooming == true){
    
        // Set zooming to false
        zooming = false;
        zoom_initialised = false;
        
        // Revert cursor
        $("body")
            .css("cursor", "");
        
        // Fade out all the zooming stuff
        zoom_large_image.fadeOut();
        zoom_screen.fadeOut();
        zoom_preload.hide();
        zoom_area.fadeOut();
        zoom_lens.fadeOut();
        zoom_shadow.fadeOut();
        
        // Show zoom icon
        zoom_icon
            .fadeIn();
        
    }
    
}

function toiMoveLens()
{
    // Determine position depending on mouse coordinates
    lens_x = mouse_x - zoom_lens.width()/2 + 1;
    lens_y = mouse_y - zoom_lens.height()/2 + 1;    
    
    // Add constraints
    var lens_max_x = lens_max_y = 0;
    lens_max_x = zoom_source_width - zoom_lens.width() + 2;
    lens_max_y = zoom_source_height - zoom_lens.height() + 2;
    
    if(lens_x < 1){
        lens_x = 1;
    } else if (lens_x > lens_max_x){
        lens_x = lens_max_x;
    }
    if(lens_y < 1){
        lens_y = 1;
    } else if (lens_y > lens_max_y){
        lens_y = lens_max_y;
    }

    // Move lens in relation to mouse position
    zoom_lens
        .css("top", lens_y + "px")
        .css("left", lens_x + "px");
    
    // Move thumb image in opposite direction
    zoom_lens
        .find("img")
        .css("top", -lens_y + 1 + "px")
        .css("left", -lens_x + 1 + "px");
}

// Move the main zoom image depending on the position of the lens
function toiMoveMainImage()
{
    if(typeof(zoom_large_image) != "undefined"){
        // Determine position
        main_zoom_x = lens_x * (1/w_factor);
        main_zoom_y = lens_y * (1/h_factor);
        
        // Constraints
        var main_max_x = main_max_y = 0;
        main_max_x = zoom_large_image.width() - zoom_area.width();
        main_max_y = zoom_large_image.height() - zoom_area.height();
        if(main_zoom_x > main_max_x){
            main_zoom_x = main_max_x;
        }
        if(main_zoom_y > main_max_y){
            main_zoom_y = main_max_y;
        }
        
        // Move that sucka
        zoom_large_image
            .css("top", -main_zoom_y + "px")
            .css("left", -main_zoom_x + "px");
    }
}








function showError(title) {
    document.getElementById('cart_error').innerHTML = title;
    $("#cart_error").show();
}


function toggleColourOptions(colour_item){
    
    colour_item = $(colour_item);
    
    var colour = colour_item.attr("title");

    // Show colour as selected
    colour_item
        .siblings("a")
        .removeClass("current");
    colour_item
        .addClass("current");
    
    // Hide error
    $("#cart_error").hide();

    // Show the available sizes correspondent with this colour
    $("#sizes span")
        .each(function(){
            if($(this).attr("id") == "size_" + colour){
                $(this).show();
            } else {
                $(this).hide();
            }
        });

    // show the right image
    $("#product_main_image div")
        .each(function(){
            if($(this).hasClass("product_main_image_" + colour)){
                $(this).show();
            } else {
                $(this).hide();
            }
        });

}

function setCurrentSize (element){
    
    element = $(element);
    
    if(element.get(0).tagName == "A"){
        var lis = element.parents("#sizes").find("a");
        var mode = "single";
    } else {
        var lis = element.find("a");
        var mode = "bulk";
    }

    // Which size is selected?
    var selected_obj;
    lis
        .each(function(){
                        
            if ((mode == "bulk" && $(this).attr("name").split("-")[0] == $("#product_size").val()) || $(this).attr("id") == element.attr("id")) {
                if($(this).attr("id") == "unavailable" ) {
                    $(this)
                        .removeClass("current")
                        .addClass("disabled");
                } else {
                    $(this)
                        .removeClass("disabled")
                        .addClass("current");
                    $("#cart_error").hide();
                }
                selected_obj = $(this);   
            } else if ($(this).hasClass("current")) {
                $(this)
                    .removeClass("current");
            }
            
        });
    
    // set selected size id
    if(typeof(selected_obj) != "undefined"){
        $("#product_size").val(selected_obj.attr("name").split("-")[0]);
        $("#cart_obj_guid").val(selected_obj.attr("name").split("-")[1]);
    } else {
        resetGUID();
    }
    
}

function resetGUID() {
    $("#product_size").val("");
    $("#cart_obj_guid").val("");
}

function checkAddToCart(){
    
    var form = $("#cart_add");
    if(form.size() == 0){
        return false;
    }

    if ($("#cart_obj_guid").val() != ""){
        form.submit();
    } else {
        $('#cart_error').show();

    }
}

function updateCartByLineItem (amount, id) {
	// update line
	var display_obj = document.getElementById("display_" + id);
	var price_per_item = document.getElementById("pp_" + id).value;
	var new_sub = amount * price_per_item;
	display_obj.innerHTML = new_sub.toFixed(2);
	document.getElementById("st_" + id).value = new_sub;
	
	// update total
	var form_obj = getParentNode(display_obj, "FORM");
	
	var new_total = 0;
	
	// get all the subtotals
	var inputs = form_obj.getElementsByTagName("INPUT");
	for (var j = 0; j < inputs.length; j++) {
		if (inputs[j].name == "subtotal" && inputs[j].type == "hidden"){
			new_total += parseInt(inputs[j].value);
		}		
	}
	document.getElementById("grand_total").innerHTML = new_total.toFixed(2);
}

function getParentNode (child_node, tag_name){
    var this_parent = child_node.parentNode;
    while (this_parent.tagName.toUpperCase() != "BODY"){
        if (this_parent.tagName.toUpperCase() == tag_name){
            return this_parent;
        }
        this_parent = this_parent.parentNode;
    }
    return false;
}





// Email validation
function checkIsValidEmail(elem, id_to_apply_error_class){

    var my_value = getElementValue(elem);

    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/;

    if (!emailFilter.test(my_value) || illegalChars.test(my_value)) {
        var my_class = document.getElementById(id_to_apply_error_class).className;
        document.getElementById(id_to_apply_error_class).className = my_class.replace(/error/i,'');
        document.getElementById(id_to_apply_error_class).className += ' error';
    }

}

// Function to trigger onblur on tab out
function loadedTabBlur(e,elem)
{
    if (window.event){
        keynum = e.keyCode
    } else if (e.which) {
        keynum = e.which
    }

    if (keynum == 9 && elem.onblur){
        elem.onblur();
    }
}

// Element showing/hiding

function toggleElement(element_id)
{
    var element = document.getElementById(element_id);
    if (element) {
        if (element.style.display == "") {
            element.style.display = "none";
        } else {
            element.style.display = "";
        }
    }
}

function showElement(element_id,type)
{

    if (type == '' || type == undefined){
        type = 'block';
    }

    var element = document.getElementById(element_id);
    if (element) {
        element.style.display = type;
    }
}

function hideElement(element_id)
{
    var element = document.getElementById(element_id);
    if (element) {
        element.style.display = "none";
    }
}

function radioToggle(elem,show,id){

    if (elem.checked == true){
        if (show == true){
            showElement(id);
        } else {
            hideElement(id);
        }
    } else {
        if (show == true){
            hideElement(id);
        } else {
            showElement(id);
        }
    }

}






// Check if a value is numeric
function is_numeric(value)
{
   if ((isNaN(value)) || (value.length == 0))
      return false;
   else
      return true;
}

// Get value of any form element

function getElementValue(elem)
{

    if (elem.tagName == 'SELECT'){
        return elem.options[elem.selectedIndex].value;
    } else if (elem.tagName == 'TEXTAREA'){
        return elem.innerHTML;
    } else if (elem.tagName == 'INPUT'){
        var my_type = elem.getAttribute('type');
        if (my_type == 'text'){
            return elem.value;
        } else if (my_type == 'radio' || my_type == 'checkbox'){
            if (elem.checked == true){
                return 1;
            } else {
                return "";
            }
        }
    }

}

// Check if form element is empty or has a value

function checkIfEmpty(elem, id_to_apply_error_class)
{

    var my_value = getElementValue(elem);

    if (my_value == "") {
        var my_class = document.getElementById(id_to_apply_error_class).className;
        document.getElementById(id_to_apply_error_class).className = my_class.replace(/error/i,'');
        document.getElementById(id_to_apply_error_class).className += ' error';
        return true;
    }
    
    return false;
    
}

function checkIfValue(elem, id_to_remove_error_class)
{

    var my_value = getElementValue(elem);

    if (my_value != "") {
        var my_class = document.getElementById(id_to_remove_error_class).className;
        document.getElementById(id_to_remove_error_class).style.display = '';
        document.getElementById(id_to_remove_error_class).className = my_class.replace(/error/i,'');
        return true;
    }
    
    return false;
}

function checkFormValidation (form){
    var form_elems = document.getElementById(form).getElementsByTagName('INPUT');
    var is_empty = false;
    for (var n = 0; n < form_elems.length; n++){
    	var wrapper = document.getElementById(form_elems[n].id + '_req');
        if (wrapper && wrapper.style.display != "none"){
            if (checkIfEmpty(form_elems[n], form_elems[n].id + '_req')){
            	is_empty = true;
            	console.log(form_elems[n].id);
            }
        }
    }
    
    if (is_empty){
    	return false;
    }
    
    return true;

}


// Add event listeners for IE

function addEvent(obj,evt,fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt,fn,false);
    } else if (obj.attachEvent) {
        obj.attachEvent('on'+evt,fn);
    }
}


