/* top select boxes helper */
function selectBox(box, valbox)
{
    $(box + " li a").click(function()
    {
        var selectedValue = $(this).attr('href');
        var label = $(box + "-trigger")
        $(valbox).val(selectedValue);
        label.html($(this).html())
        return false;
    });
}

/* email validation */
function emailCheck (emailStr) {
    var emailPat=/^(.+)@(.+)$/
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validChars="\[^\\s" + specialChars + "\]"
    var quotedUser="(\"[^\"]*\")"
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom=validChars + '+'
    var word="(" + atom + "|" + quotedUser + ")"
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
    var matchArray=emailStr.match(emailPat)
    if (matchArray==null) {
    	    	return false
    }
    var user=matchArray[1]
    var domain=matchArray[2]
    
    if (user.match(userPat)==null) {
                        return false
    }
    
    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null) {
    	    for (var i=1;i<=4;i++) {
    	        if (IPArray[i]>255) {
    	                    		return false
    	        }
            }
            return true
    }
    
    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
    	            return false
    }
    
    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if (domArr[domArr.length-1].length<2 || 
            domArr[domArr.length-1].length>3) {
                    return false
    }
    
    if (len<2) {
         return false
    }
    return true;
}

$(document).ready(function()
{
    /* load the slideshow plugin for the product images */
    $("div#experience-image").slideView();
    $("div#press").slideView();
    
    /* lang and search dropdowns */
    $(".ls-dropdown").each(function()
    {
        var shown = false;
        var time = false;
        
        $(".ls-dropdown").hover(function()
        {
            if (time) clearTimeout(time);
            if (shown)
            {
                return;
            } else {
                $(".ls-dropdown-menu").hide();
                $(this).siblings(".ls-dropdown-menu").slideDown();
                shown = true;
            }
            return false;
        }, function()
        {
            if (time) clearTimeout(time);
            var menu = $(this);
            time = setTimeout(function()
            {
                menu.siblings(".ls-dropdown-menu").slideUp();
                shown = false;
            }, 100);
            return false;
        });
        
        $(".ls-dropdown-menu").hover(function()
        {
            if (time) clearTimeout(time);
            if (shown)
            {
                return;
            } else {
                $(this).slideDown();
                shown = true;
            }
            return false;
        }, function()
        {
            if (time) clearTimeout(time);
            var menu = $(this);
            time = setTimeout(function()
            {
                menu.slideUp();
                shown = false;
            }, 100);
            return false;
        });
    });
        
    $(".ls-dropdown-menu").find("a").click(function()
    {
        $(".ls-dropdown-menu").hide();
    });
    
    selectBox("#cat-menu", "#search-cat");
    selectBox("#price-menu", "#search-price");
    
    /* lang buttons */
    $("#english").click(function()
    {
        $.ajax({
            url: "/i18n/setlang/",
            type: 'POST',
            data: "language=en-us&next="+$("#lang_path").val(),
            success: function(data, textStatus) { location.href = location.href },
            async: false,
            cache: false
        });
    });
    
    $("#chinese").click(function()
    {
        /*$.ajax({
            url: "/i18n/setlang/",
            type: 'POST',
            data: "language=zh-cn&next="+$("#lang_path").val(),
            success: function(data, textStatus) { location.href = location.href },
            async: false,
            cache: false
        });*/
    });
    
    /* sidemenu submenu */
    $(".sidemenu-sub-trigger").each(function()
    {
        /*
            On this function, shown works differently from the others. Here shown
            saves the name of the shown menu and before any menu it's shown, it's
            checked if that menu is not the one being shown already, and if not,
            that menu is hidden (only that one, and not all of it's class)
        */
        var shown = false;
        var time = false;
        
        $(".sidemenu-sub-trigger, .sidemenu-sub").hover(function()
        {
            if (time) clearTimeout(time);
            if($(this).hasClass("sidemenu-sub"))
            {
                if(shown != "#"+$(this).attr("id") && shown)
                {
                    $(shown).hide();
                }
                $(this).show();
                shown = "#"+$(this).attr("id");
            } else {
                var submenuid = "#" + $(this).attr("id") + "menu";
                if(shown != submenuid && shown)
                {
                    $(shown).hide();
                }
                $(submenuid).show();
                shown = submenuid;
            }
            return false;
        }, function()
        {
            if (time) clearTimeout(time);
            var thisVar = $(this)
            time = setTimeout(function()
            {
                if($(thisVar).hasClass("sidemenu-sub"))
                {
                    $(".sidemenu-sub").hide();
                } else {
                    $(thisVar).parent().parent().parent().find(".sidemenu-sub").hide();
                }
                shown = false;
            }, 100);
            return false;
        });
    });
    
    
    /* events for list on-hover */
    $(".grid-item").each(function()
    {
        $(this).hover(
        function()
        {
            var item = $(this).attr("id");
            var splitstr = item.split("-");
            var info = "#info-"+ splitstr[1];
            $(".grid-info").hide();
            $(info).show();
        },function()
        {});
    }
    );
    
    $(".grid-info").each(function()
    {
        $(this).hover(
        function()
        {},function()
        {
            var info = "#" + $(this).attr("id");
            $(info).hide();
        });
    });
    
    $(".grid-block").each(function()
    {
        $(this).click(function()
        {
            var link = $(this).find("h4").find("a").attr("href");
            document.location = link;
            return false;
        });
    });
    
    /* ajax event for order button */
    $("#experience-add a").click(function()
    {
        var prodid = $("#prodid").val();
        $("#experience-add").hide();
        $("#shopcart a").load("/experiences/add_to_cart/"+prodid+"/");
        $(".added").show();
        setTimeout(function()
        {
            $(".added").fadeOut();
        }, 2000);
        return false;
    });
    
    $("#wishlist-add a").click(function()
    {
        var prodid = $("#prodid").val();
        $("#wishlist-add").load("/users/wishlistadd/"+prodid+"/")
        setTimeout(function()
        {
            $("#wishlist-add").fadeOut();
        }, 2000);
        return false;
    });
    
    $("#wishlist-group .remove").click(function()
    {
        $("#wishlist-group").load($(this).attr("href"));
        $(".removed").show();
        setTimeout(function()
        {
            $(".removed").fadeOut();
        }, 2000);
        return false;
    });
    
    $("#bdayadd").submit(function()
    {
        $.ajax({
            url: "/users/bdayadd/",
            type: 'POST',
            data: "name="+$("#name").val()+"&date="+$("#date").val(),
            cache: false,
            success: function()
            {
                $("#bday-group").load("users/bdaylist/index.html");
                $(".added").show();
                setTimeout(function()
                {
                    $(".added").fadeOut();
                }, 2000);
            },
            error: function()
            {
                $("#bdayerror").show();
                setTimeout(function()
                {
                    $("#bdayerror").fadeOut();
                }, 2000);
            }
        });
        return false;
    });
    
    $("#bday-group .remove").click(function()
    {
        $("#bday-group").load($(this).attr("href"));
        $(".removed").show();
        setTimeout(function()
        {
            $(".removed").fadeOut();
        }, 2000);
        return false;
    });
    
    /* ajax events for item removal */    
    $(".remove-all").click(function()
    {
        var prodid = $(this).parents('.cart-row').find('.prodid').val();
        var type = $(this).parents('.cart-row').find('.itemtype').val();
        $("#shopcart a").load("/experiences/remove_from_cart/"+prodid+"/"+type+"/");
        $("#cart").load("experiences/cart/index.html");
        return false;
    });
    
    /* add more persons to an experience */
    $(".add-persons").click(function(){
        var this_id = $(this).attr("id");
        var split_id = this_id.split("-");
        var extra_persons = $("#extra_persons-"+split_id[1]).val();
        $("#extra-"+split_id[1]).load("/experiences/add_persons/"+extra_persons+"/"+split_id[1]+"/");
    });
    
    
    /* add a voucher to the cart */
    $(".voucher-add").click(function(){
        $("#shopcart a").load($(this).attr("href"));
        if($("#cart").length) $("#cart").load("experiences/cart/index.html");
        return false;
    });
      
	  
	  

    
    /* js events for product actions */
    $("#more-info a").click(function()
    {
        var id = $(this).attr("href");
        $("#experience-info").load("/experiences/product/"+id+"/2/");
        $(this).show();
        return false;
	
    });
    
    $(".print-me").click(function()
    {
        window.print();
    });
    
    $("#mail-friend").click(function()
    {
        function mail_friend(v, m)
        {
            if(v)
            {
                ymail = m.find("#yourmail");
                if(emailCheck(ymail.val()) == false)
                {
                    $.prompt("Your e-mail is not valid");
                    return false;
                }
                yname = m.find("#yourname");
                if(yname.val() == '')
                {
                    $.prompt("Your name is empty");
                    return false;
                }
                fmail = m.find("#friendmail");
                if(emailCheck(fmail.val()) == false)
                {
                    $.prompt("Your friend's e-mail is not valid");
                    return false;
                }
                
                pid = $("#more-info a").attr("href");
                $.ajax({
                    url: "/experiences/mailfriend/",
                    type: 'POST',
                    data: "ymail="+ymail.val()+"&yname="+yname.val()+"&fmail="+fmail.val()+"&pid="+pid,
                    cache: false,
                    success: function()
                    {
                        $.prompt("Your suggestion was sent successfully.")
                    },
                    error: function()
                    {
                        $.prompt("There was a problem sending your suggestion. Please, try again.")
                    }
                });
                return true;
            }
        }
        
        var mailfriendwindow = "";
        $.prompt(mailfriendwindow,
            {
                buttons: { Send: true, Cancel: false },
                callback: mail_friend
            });
        return false;
    });
    
    /* js event for name loading on front page blocks */
    $(".front-page-block a").hover(function()
    {
        var href = $(this).attr("href");
        $(this).parents(".front-page-block").find(".label").load(href+"3/");
    }, function()
    {
        $(this).parents(".label").html("");
    });
    
    
    /* events for booking */
    $("#receive-mail").click(function() { $(".send-to").show(); return false; });
    $(".send-to input").click(function() {
        $(".where-to").show();
    });
    
    $(".where-to input").click(function() {
        if($(this).val() == "hongkong")
        {
            $(".delivery-charge").show();
        } else {
            $(".delivery-charge").hide();
        }
        $(".mail-type").show();
    });
    
    $(".mail-type input").click(function() {
        $(".submit-delivery").show();
    });
    
    $("#instant input").click(function() {
        $("#instant-notice").show();
    });
    
    $(".datepickerfield").datepicker();
    
    
    /* payment form - save user credit card info*/
    $("#payment-form").submit(function()
    {
        var tid = $("#id_orderRef").val();
        var cardno = $("#id_cardNo").val();
        var cardtype = $("#id_pMethod option:selected").val();
        $.ajax({
                url: "/users/cardinfo/",
                type: 'POST',
                data: "tid="+tid+"&cardno="+cardno+"&cardtype="+cardtype,
                cache: false
        });
        return true;
    });
    
    
    /* activation form */
    $("#activate-form").submit(function()
    {
        var code = $("#code").val();
	var card = $("#card").val();
        $.ajax({
                url: "/experiences/redeem/",
                type: 'POST',
                data: "code="+code+"&card="+card,
                cache: false,
                success: function(html)
                {
                    $("#activation").html(html);
                }
        });
        return false;
    });
    
    /* recovery notification */
    $("#password-recovery").submit(function(){
        var email = $("#email").val();
        $.ajax({
                url: "/users/recovery/",
                type: 'POST',
                data: "email="+email,
                cache: false,
                success: function(html)
                {
                    $("#recovery-notice").show();
                }
        });
        return false;
    });
    
    $("#experience-voucher, #open-voucher").hover(function()
    {
        $(this).css("background-image", "url(../images/"+$(this).attr("id")+"-over.png)");
        $(this).find("h3").css("color", "#fff");
        $("#"+$(this).attr("id")+"-text").show();
    }, function()
    {
        $(this).css("background-image", "url(../images/"+$(this).attr("id")+".png)");
        $(this).find("h3").css("color", "#004282");
        $("#"+$(this).attr("id")+"-text").hide();
    });
});

