/*
--------------------------------------- 

The Phone House - Javascript

--------------------------------------- 
*/



/* MENU
*************************************/

$(function() {

    var hovering = false;
    var hovering_submenu = false;

    function menuOver() {

            // caso este menu tenha o atributo rel
            // marcar como actual e mostrar o submenu #<rel>
        if ($(this).attr('rel').length > 0) {
            $(this).addClass('hover');


            if ($(this).hasClass('right')) {
                var target = '#' + $(this).attr('rel');
                var offsetleft = Math.floor($(this).position().left - ($(target).outerWidth() - $(this).width())) + 125;

                //var offsetRight = Math.floor($(this).position().left + $(this).width());

                $(target).css({ left: offsetleft + 'px', display: 'none' }),
                 $(target).stop(false, true).slideToggle('slow');
            }
            else {
                var offsetleft = Math.floor($(this).position().left),
				    target = '#' + $(this).attr('rel');
                $(target).css({ left: offsetleft, display: 'block' });
            }

            hovering = true;
            hovering_submenu = false;
        }

    }

    function menuOut() {
        if (hovering === true && hovering_submenu === true) {
            return;
        } else {
            if ($(this).attr('rel').length > 0) {
                var target = '#' + $(this).attr('rel');
                if ($(this).hasClass('right')) {
                    $(target).css({ display: 'block' });
                    $(target).stop(false, true).slideToggle('slow');
                }
                else
                    $(target).css({ display: 'none' });
            }
            $(this).removeClass('hover');
        }
    }

    function submenuOver() {
        var id = $(this).attr('id'),
			target = '#navigation a[rel=' + id + ']';

        if (!$(target).hasClass('hover')) {
            $(target).addClass('hover');
        }

        $(this).css('display', 'block');
        hovering = true;
        hovering_submenu = true;
    }

    function submenuOut() {
        var id = $(this).attr('id'),
			target = '#navigation a[rel=' + id + ']';

        $(target).removeClass('hover');

        if ($(target).hasClass('right')) {
            $(this).css('display', 'block');
            $(this).slideToggle('slow');
        }
        else
            $(this).css('display', 'none');
        hovering = false;
        hovering_submenu = false;
    }

    var mainmenuconfig = {
        interval: 20,
        over: menuOver,
        timeout: 200,
        out: menuOut
    }

    var submenuconfig = {
        interval: 1,
        over: submenuOver,
        timeout: 100,
        out: submenuOut
    }

    $('#submenus .submenu').hoverIntent(submenuconfig);
    $('#navigation a').hoverIntent(mainmenuconfig);

});


var tph = {}

//$(document).ready(function(){ tph.init(); })

/**
 * Init function
 */
tph.init = function() {
    for (prop in this) {
        if (typeof this[prop].init == 'function') {
            this[prop].init();
        }
    }
}


/**
 * Clean form fields on focus and set the value
 * again if on blur it's empty
 */
tph.cleanFormFields = {
	init: function () {
		$(':input')
			.bind('focus', function() { if ($(this).val() == $(this).attr('title')) $(this).val(''); })
			.bind('blur', function() { if ($(this).val() == '') $(this).val($(this).attr('title')); });
	}
}

/**
 * Add class .first to specific elements that need
 * different styles from their sibblings
 */
tph.firstElements = {
	init: function () {
		$('#footer .section:first, #navigation li:first, .center .col_1:first').addClass('first');
	}
}

/**
 * Quick search 
 */
tph.searchSectionOptions = {
    settings: {
        displaySelected: '#section_selected',
        valueSelected: '#section_selected_value',
        optionsList: '#section_options',
        showOptionsTrigger: '#section_show_options'
    },
    init: function() {
        $(this.settings.showOptionsTrigger).bind('click', this.optionsList.toggle);
        $(this.settings.displaySelected).bind('click', this.optionsList.toggle);
        $(this.settings.optionsList).find('a').bind('click', this.optionClick);
        if ($('#gallery').length)
            $('#gallery a').lightBox();
       
    },
    optionsList: {
        show: function(element) {
            $(tph.searchSectionOptions.settings.optionsList).slideDown('fast');
        },
        hide: function() {
            $(tph.searchSectionOptions.settings.optionsList).slideUp('fast');
        },
        toggle: function() {
            var element = $(tph.searchSectionOptions.settings.optionsList);
            if (element.is(':visible')) {
                tph.searchSectionOptions.optionsList.hide();
            } else {
                tph.searchSectionOptions.optionsList.show();
            }
            return false;
        }
    },
    optionClick: function() {
        var display = $(tph.searchSectionOptions.settings.displaySelected),
			value = $(tph.searchSectionOptions.settings.valueSelected),
			option = $(this);
        display.html(option.html());
        value.val(option.attr('rel'));
        tph.searchSectionOptions.optionsList.hide();
        return false;
    }
}


/**
 * Cart item quantity
 
tph.cartItemQuantity = {
	settings: {
		increaseButton: '.idbutton.plus',
		decreaseButton: '.idbutton.minus',
		quantityBox: '.quantitybox',
		interval: 1
	},
	init: function() {
		$(tph.cartItemQuantity.settings.increaseButton).bind('click', tph.cartItemQuantity.increaseQuantity);
		$(tph.cartItemQuantity.settings.decreaseButton).bind('click', tph.cartItemQuantity.decreaseQuantity);
	},
	increaseQuantity: function() {
		var eleQtt = $(this).siblings('input');
		var intQtt = tph.cartItemQuantity.currentQuantity(this);
		
		eleQtt.val(parseInt(intQtt + tph.cartItemQuantity.settings.interval));
		
		return false;
	},
	decreaseQuantity: function() {
		var eleQtt = $(this).siblings('input');
		var intQtt = tph.cartItemQuantity.currentQuantity(this);
		
		if (intQtt > tph.cartItemQuantity.settings.interval) {
			eleQtt.val(parseInt(intQtt - tph.cartItemQuantity.settings.interval));
		}
		
		return false;
	},
	currentQuantity: function(eleClicked) {
		var currentQtt = $(eleClicked).siblings(tph.cartItemQuantity.settings.quantityBox).val();
		
		if (parseInt(currentQtt) != currentQtt - 0) {
			currentQtt = 0;
		}
		
		return parseInt(currentQtt);
	}
}*/

/**
 * Checkout - payment method
 */
tph.paymentMethod = {
	settings: {
		optionsContainer: '.payment_options',
		detailsContainer: '.payment_details'
	},
	init: function() {
		$(tph.paymentMethod.settings.optionsContainer).find(':input[type=radio]').change(tph.paymentMethod.swap);
		$(tph.paymentMethod.settings.optionsContainer).find(':input[type=radio]:checked').change();
	},
	swap: function() {
		$(tph.paymentMethod.settings.detailsContainer).find('.detail').fadeOut('normal');
		$("#detail_" + $(this).val()).fadeIn('normal');
		return false;
	},
	checkSelected: function() {
		document.write('hello world!');
	}
}

/**
 * Filter
 */
tph.searchFilters = {
    settings: {
        filterItem: '.filter_item',
        optionsList: '.filter_item_options',
        optionsItems: '.filter_item_options li'
    },
    init: function() {
        $(tph.searchFilters.settings.filterItem).find('div').bind('click', tph.searchFilters.labelClick);
      //  $(tph.searchFilters.settings.optionsItems).bind('click', tph.searchFilters.optionClick);
    },
    showOptions: function(element) {
        $(element).css('z-index', 100).parent().css('z-index', 100);
        $(element).slideDown('fast');
    },
    hideOptions: function(element) {
        $(element).slideUp('fast')
        $(element).css('z-index', 0).parent().css('z-index', 0);
    },
    toggleOptions: function(element) {
        if ($(element).is(':visible')) {
            tph.searchFilters.hideOptions(element);
        } else {
            tph.searchFilters.showOptions(element);
        }
    },
    labelClick: function() {
        tph.searchFilters.toggleOptions($(this).siblings('ul'));
        return false;
    },
    optionClick: function() {
        $(this).parents('.filter_item').children('div').html($(this).html());
    //    $(this).parents('.filter_item').children('input').val($(this).attr('rel'));
        tph.searchFilters.hideOptions($(this).parents('ul'));

//        alert('yay');
        // copia o valor escolhido para o hidden field dentro do link
//        var hidden_value = $(this).children();
//        alert(hidden_value.length);
//        if (hidden_value.length > 0)
//            $('#' + hidden_value[1].id).val($(this).attr('rel'));
    }
}

/* Validacoes
---------------------------------------------*/

function ValidateTextBox(source, args) {
    var controltovalidate = source.controltovalidate;
    var is_visible = $("#" + controltovalidate).is(':visible');
    if (is_visible) {
        var is_valid = ($("#" + controltovalidate).val() != "" && $("#" + controltovalidate).val() != 'Max. 1000 caracters');
        $("#" + controltovalidate).css("background-color", is_valid ? "white" : "#FFFFCC");
        args.IsValid = is_valid;
    }
    else {
        $("#" + controltovalidate).css("background-color", "white");
        args.IsValid = true;
    }
}

function ValidateTextBoxZoomed(source, args) {
    var controltovalidate = source.controltovalidate;
    var is_visible = $("#" + controltovalidate + "__zoomed").is(':visible');
    if (is_visible) {
        var is_valid = ($("#" + controltovalidate + "__zoomed").val() != "" && $("#" + controltovalidate + "__zoomed").val() != 'Max. 1000 caracters');
        $("#" + controltovalidate + "__zoomed").css("background-color", is_valid ? "white" : "#FFFFCC");
        args.IsValid = is_valid;
    }
    else {
        $("#" + controltovalidate + "__zoomed").css("background-color", "white");
        args.IsValid = true;
    }
    if (!is_valid) {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "inline");
    }
    else {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "none");
    }
}

function ValidateEmailBox(source, args) {
    var emailPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var controltovalidate = source.controltovalidate;
    var is_visible = $("#" + controltovalidate).is(':visible');
    if (is_visible) {
        var is_valid = (
            $("#" + controltovalidate).val() != ""
            && emailPattern.test($("#" + controltovalidate).val())
        );

        $("#" + controltovalidate).css("background-color", is_valid ? "white" : "#FFFFCC");
        args.IsValid = is_valid;
    }
    else {
        $("#" + controltovalidate).css("background-color", "white");
        args.IsValid = true;
    }
}

function ValidateEmailBoxEmailItem(source, args) {
    var emailPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var controltovalidate = source.controltovalidate;

    var is_valid = (
        $("#zoom_content #" + controltovalidate + "__zoomed").val() != ""
        && emailPattern.test($("#zoom_content #" + controltovalidate + "__zoomed").val())
    );

    $("#zoom_content #" + controltovalidate + "__zoomed").css("background-color", is_valid ? "white" : "#FFFFCC");
    args.IsValid = is_valid;
    if (!is_valid) {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "inline");
    }
    else {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "none");
    }
}

function ValidateEmailBoxEmailItemIgnoreEmpty(source, args) {
    var emailPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var controltovalidate = source.controltovalidate;

    var is_valid = (
        $("#zoom_content #" + controltovalidate + "__zoomed").val().trim() == ""
        || emailPattern.test($("#zoom_content #" + controltovalidate + "__zoomed").val().trim())
    );

    $("#zoom_content #" + controltovalidate + "__zoomed").css("background-color", is_valid ? "white" : "#FFFFCC");
    args.IsValid = is_valid;
    if (!is_valid) {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "inline");
    }
    else {
        $("#zoom_content span." + controltovalidate + "__zoomed").css("display", "none");
    }
}

function ValidatePhoneBox(source, args) {
    var emailPattern = /^([0-9+-.()#]*)$/i;
    var controltovalidate = source.controltovalidate;
    var is_visible = $("#" + controltovalidate).is(':visible');
    if (is_visible) {
        var is_valid = (
            $("#" + controltovalidate).val() != ""
            && emailPattern.test($("#" + controltovalidate).val())
        );

        $("#" + controltovalidate).css("background-color", is_valid ? "white" : "#FFFFCC");
        args.IsValid = is_valid;
    }
    else {
        $("#" + controltovalidate).css("background-color", "white");
        args.IsValid = true;
    }
}

/**
* Advanced search
*/
tph.advancedSearch = {
    settings: {
        sectionToggle: '.filter_item h4',
        sectionOptions: '.filter_item_options'
    },
    init: function() {
        $(tph.advancedSearch.settings.sectionToggle).click(tph.advancedSearch.toggleOptions);
    },
    toggleOptions: function() {
        $(this).parent().find(tph.advancedSearch.settings.sectionOptions).slideToggle('fast');
        $(this).toggleClass('open');
    }
}

function setAddedCart(imgUrl, spanCart) {
    $("#divAddedCart img").attr('src', imgUrl);
    $("#divAddedCart #spanAddedCart").text(spanCart);
}

function showAddedCart() {
    $("#divAddedCart").fadeIn(1500).fadeTo(1500, 1).fadeOut('slow', function() { $("#divAddedCart img").attr('src', ''); $("#divAddedCart span").val(''); });
}

