﻿function _doPostBack(eventName, eventArgs) {
    try {
        var prm = Sys.WebForms.PageRequestManager.getInstance();

        if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
            prm._asyncPostBackControlIDs.push(eventName);
        }

        if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
            prm._asyncPostBackControlClientIDs.push(eventName);
        }
    } catch (e) { }

    __doPostBack(eventName, eventArgs);
}
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
function DrawImg1(ele, boxWidth, boxHeight) {

    var imgWidth = $(ele).width();
    var imgHeight = $(ele).height();
    //比较imgBox的长宽比与img的长宽比大小
    if ((boxWidth / boxHeight) >= (imgWidth / imgHeight)) {
        //重新设置img的width和height
        $(ele).width((boxHeight * imgWidth) / imgHeight);
        $(ele).height(boxHeight);
        //让图片居中显示
        // var margin = (boxWidth - $(ele).width()) / 2;
        // $(ele).css("margin-left", margin);
    }
    else {
        //重新设置img的width和height
        $(ele).width(boxWidth);
        $(ele).height((boxWidth * imgHeight) / imgWidth);
        //让图片居中显示
        var margin = (boxHeight - $(ele).height()) / 2;
        $(ele).css("margin-top", margin);
    }
}
function CallWebService(_methord, _data, _callback) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/WebService.asmx/" + _methord,
        data: _data,
        dataType: 'json',
        success: _callback,
        cache: false,
        complete: function (XMLHttpRequest, textStatus) {
            if (textStatus != "success") {
                showError(XMLHttpRequest.responseText);
            }
        }
    });
}

function AddFavorite(productId) {
    CallWebService("AddFavorite", "{productID:'" + productId + "'}", function (result) {
        $("#favorateList").html(result.d);
        showTips("操作成功！", 400, 3);
    });
}
function ValidateCreditCardNumber(cn, callback) {
    CallWebService("ValidateCreditCardNumber", "{cardNumber:'" + cn + "'}", function (result) {
        callback(result.d);
    });
}

function AddLineItem(productId, variantId, quantity) {
    CallWebService("AddLineItem", "{productId:'" + productId + "',variantId:'" + variantId + "',quantity:'" + quantity + "'}", function (result) {
        showTips("操作成功！", 400, 3);
    });
}

function DeleteFavorite(id) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "WebService.asmx/DeleteFavorite",
        data: "{id:'" + id + "'}",
        dataType: 'json',
        complete: function (XMLHttpRequest, textStatus) {
        },
        success: function (result) {
            $("#favorateList").html(result.d);
            showTips("操作成功！", 400, 3);
        }
    });
}

var pnotify_showError;
function removeError() {
    if (pnotify_showError != null) pnotify_showError.pnotify_remove();
    $("#_errorMsg").text("");
    $("#_errorMsgBox").hide();
}
function showErrorMsg(tips) {
    showError(tips);
}
function showError(tips) {
    if ($("#_errorMsg").length > 0) {
        $("#_errorMsg").text(tips);
        $("#_errorMsgBox").show();

        return;
    }
    alert(tips);
    return;
    removeError();
    pnotify_showError = $.pnotify({
        pnotify_title: '错误',
        pnotify_text: tips,
        pnotify_opacity: 1,
        pnotify_hide: false,
        pnotify_shadow: true,
        pnotify_animate_speed: "fast",
        pnotify_history: false,
        pnotify_closer: true,
        pnotify_type: "error",
        pnotify_addclass: "stack-bottomright",
        pnotify_stack: stack_bottomright


    });
}
function showTips(tips, height, time) {
    $.pnotify({
        pnotify_title: '提示',
        pnotify_text: tips,
        pnotify_opacity: 1,
        pnotify_delay: 2000, 	//显示时间（毫秒）
        pnotify_shadow: true,
        pnotify_animate_speed: "fast",
        pnotify_history: false,
        pnotify_addclass: "stack-bottomright",
        pnotify_stack: stack_bottomright
    });
}

//多個validationGroup,請用逗號分開
function validationSummary(validationGroup) {
    if (validationGroup == null) validationGroup = "";
    var groups = validationGroup.split(",");
    var ret = true;
    for (var j in groups) {

        var group = groups[j];
        for (i in Page_Validators) {
            var validator = Page_Validators[i];
            if (!IsValidationGroupMatch(validator, group)) continue;
            ValidatorValidate(validator, group, null);
            if (validator.isvalid) {
                $("#" + validator.controltovalidate).parents("tr").removeClass("error");
            }
            else {
                ret = false;
                $("#" + validator.controltovalidate).parents("tr").addClass("error");
            }

        }


    }

    return ret;
}


function tryFunction(fun) {
    try {
        fun();
    } catch (e) { }
}

var stack_bottomright = { "dir1": "up", "dir2": "left", "firstpos1": 15, "firstpos2": 15 };
var loading;
$(function () {
    tryFunction(function () {
        $("select").sSelect();

    });
    $(".Validator.Required").css("visibility", "");

    try {
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
            function () {
                //Sys.WebForms.PageRequestManager.getInstance()._scrollPosition = null;

                removeError();
                //    loading = $.pnotify({
                //        pnotify_title: '處理中...',
                //        pnotify_opacity: 1,
                //        pnotify_shadow: true,
                //        pnotify_animate_speed: "fast",
                //        pnotify_history: false,
                //        pnotify_hide: false
                //    });
            }
);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
            $("form:first").unmask();
            //                    $(".Validator.Required").css("visibility", "");
            //            tryFunction(function () { $("select").sSelect(); });

            //            if (loading != null)
            //                loading.pnotify_remove();

        });
    } catch (e) { }
});



//(function($) {
//	$.extend({
//		pnotify_remove_all: function () {...},		//函数：去除所有提示
//		pnotify_position_all: function () {...},	//函数：定位所有提示
//		pnotify: function(options) {...				//函数：根据options生成一个提示
//			pnotify.pnotify = function(options) {...};	//函数：更新提示
//			pnotify.pnotify_queue_position = function() {...};	//函数：将位置函数加入队列以使其不重复执行
//			pnotify.pnotify_display = function() {...};	//函数：显示提示
//			pnotify.pnotify_remove = function() {...};	//函数：去除提示
//			pnotify.animate_in = function(callback){...};	//函数：以动画方式显示
//			pnotify.animate_out = function(callback){...};	//函数：以动画方式隐藏
//			pnotify.pnotify_cancel_remove = function() {...};	//函数：取消所有隐藏提示的计时器
//			pnotify.pnotify_queue_remove = function() {...};	//函数：添加隐藏提示的计时器
//			...
//		}
//	});

//	$.pnotify.defaults = {

//		/* 属性 */
//		pnotify_title: "",				//提示框的标题
//		pnotify_text: "",				//提示框的内容
//		pnotify_addclass: "",			//添加到提示样式上的额外class
//		pnotify_history: true,			//显示一个可以可拉的菜单以回显历史提示
//		pnotify_width: "300px",			//提示框的宽度
//		pnotify_min_height: "16px",		//提示框的最小高度，可以自适应
//		pnotify_type: "notice",			//提示框的类型，值可以为：'notice'、'error'
//		pnotify_notice_icon: "ui-icon ui-icon-info",	//'notice'提示的图标class
//		pnotify_error_icon: "ui-icon ui-icon-alert",	//'error'提示的图标class
//		pnotify_animation: "fade",		//动画类型，值可以为：'none','show','fade','slide'等jQuery原生特效或者jQuery UI中的特效，也可以用以下方式指定开始和结束时的效果：{effect_in:'show',effect_out:'slide'}
//		pnotify_animate_speed: "slow",	//动画的播放速度
//		pnotify_opacity: 1,				//提示框的透明度
//		pnotify_shadow: false,			//是否显示阴影
//		pnotify_closer: true,			//是否显示关闭按钮
//		pnotify_hide: true,				//是否自动隐藏
//		pnotify_delay: 3000,			//显示时间（毫秒）
//		pnotify_mouse_reset: true,		//当鼠标经过时将显示时间的计时器重置
//		pnotify_remove: true,			//当提示框隐藏时从DOM中去除其元素
//		pnotify_insert_brs: true,		//将新行转换成br标记
//		pnotify_stack: {"dir1": "down", "dir2": "left", "push": "bottom"},	//提示框显示的位置

//		/* 事件 */
//		pnotify_before_init: null,
//		pnotify_after_init: null,
//		pnotify_before_open: null,
//		pnotify_after_open: null,
//		pnotify_before_close: null,
//		pnotify_after_close: null

//	};
//})(jQuery);

$.fn.smartFloat = function () {
    var position = function (element) {

        element.parent().css("height", element.parent().height());
        element.css("height", element.height());
        element.css("width", element.width());
        element.css("z-index", 100);

        var top = element.position().top, pos = element.css("position");
        $(window).scroll(function () {
            var scrolls = $(this).scrollTop();

            if (scrolls > top) {

                if (window.XMLHttpRequest) {
                    element.css({
                        position: "fixed",
                        top: 0
                    });
                } else {
                    element.css({
                        top: scrolls
                    });
                }
            } else {
                element.css({
                    position: "absolute",
                    top: top
                });
            }
        });
    };
    return $(this).each(function () {
        position($(this));
    });
};


jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

$(function () {
    // 支持
    $("[defaultButton]").keydown(function (event) {
        if (event.keyCode != 13) return;
        $("#" + $(this).attr("defaultButton")).click();
        event.stopPropagation();
        if (window.event) window.event.returnValue = false;
        else event.preventDefault();
        //window.event.cancelBubble = true;

    });
});


function open_pay_dialog(arg) {
    tb_open_new('/Pay.aspx?' + arg + '&TB_iframe=true&height=550&width=621&modal=false');
}

function disableButton(ele) {

    $("form:first").mask("");
    //让进度图片在屏幕居中
    var obj = $(".loadmask-msg");
    obj.css("position", "absolute");
    obj.css("top", ($(window).height() - obj.height()) / 2 + $(window).scrollTop() + "px");
    obj.css("left", ($(window).width() - obj.width()) / 2 + $(window).scrollLeft() + "px");

    //$(ele).replaceWith("<span style='display:inline-block; margin-right:6px;line-height:" + $(ele).height() + "px' ><img align=absmiddle  src='/images/ajax-loader.gif' />處理中...</span>");
}

function hiddeButton(ele) {

    //$("form:first").mask("");
    $(ele).replaceWith("<span class='loading' style='display:inline-block; margin-right:6px;line-height:" + $(ele).height() + "px' ><img align=absmiddle  src='/images/ajax-loader.gif' /></span>");
}

function CheckDataLength(source, arguments) {
    var content = arguments.Value;
    if (content.length < $(source).attr('minLength') || content.length > $(source).attr('maxLength')) {
        arguments.IsValid = false;
    }
    else {
        arguments.IsValid = true;
    }
}

function CheckEmailRegisterd(source, arguments) {
    var content = arguments.Value;
    removeError();
    CallWebService("CheckEmailRegisterd", "{email:'" + content + "'}", function (result) {
        if (result.d == "1") showError("您所填寫的郵箱地址已被註冊，請更換！");
    });
    return true;
}

/*
作用：縮放圖片
參數： ImgD：頁面元素對象 ，maxWidth：最大寬度（數值類型 如90），maxHeight:最大高度（數值類型 如90）  
*/
function DrawImage(ImgD, maxWidth, maxHeight) {

    var image = new Image();
    var iwidth = maxWidth; //定义允许图片宽度，当宽度大于这个值时等比例缩小
    var iheight = maxHeight; //定义允许图片高度，当宽度大于这个值时等比例缩小    
    image.src = ImgD.src;
    if (image.width > 0 && image.height > 0) {
        flag = true;
        if (image.width / image.height >= iwidth / iheight) {
            if (image.width > iwidth) {
                ImgD.width = iwidth;
                ImgD.height = (image.height * iwidth) / image.width;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }

            ImgD.alt = image.width + "×" + image.height;
        }
        else {
            if (image.height > iheight) {
                ImgD.height = iheight;
                ImgD.width = (image.width * iheight) / image.height;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
            ImgD.alt = image.width + "×" + image.height;
        }
    }
}

// JavaScript Document
function goTopEx() {
    var obj = document.getElementById("goTopBtn");
    function getScrollTop() {
        return document.documentElement.scrollTop;
    }
    function setScrollTop(value) {
        document.documentElement.scrollTop = value;
    }
    window.onscroll = function () { getScrollTop() > 0 ? obj.style.display = "" : obj.style.display = "none"; }
    obj.onclick = function () {
        var goTop = setInterval(scrollMove, 10);
        function scrollMove() {
            setScrollTop(getScrollTop() / 1.1);
            if (getScrollTop() < 1) clearInterval(goTop);
        }
    }
}

// JavaScript Document
function goTop() {

    if (jQuery.browser.safari) {//这里判断浏览器是否为safari
        jQuery('body').animate({ scrollTop: 0 }, 'fast');
        return false; //返回false可以避免在原链接后加上#
    }
    else {
        jQuery('html').animate({ scrollTop: 0 }, 1000);
        return false;
    }

}

function parseInt10(obj) {
    return parseInt(obj, 10);
}


function DateAdd(interval, number, date) {
    /*
    *---------------   DateAdd(interval,number,date)   -----------------
    *   DateAdd(interval,number,date)  
    *   功能:实现VBScript的DateAdd功能.
    *   参数:interval,字符串表达式，表示要添加的时间间隔.
    *   参数:number,数值表达式，表示要添加的时间间隔的个数.
    *   参数:date,时间对象.
    *   返回:新的时间对象.
    *   var   now   =   new   Date();
    *   var   newDate   =   DateAdd( "d ",5,now);
    *   author:wanghr100(灰豆宝宝.net)
    *   update:2004-5-28   11:46
    *---------------   DateAdd(interval,number,date)   -----------------
    */
    switch (interval) {
        case "y ": 
            {
                date.setFullYear(date.getFullYear() + number);
                return date;
                break;
            }
        case "q ": 
            {
                date.setMonth(date.getMonth() + number * 3);
                return date;
                break;
            }
        case "m ": 
            {
                date.setMonth(date.getMonth() + number);
                return date;
                break;
            }
        case "w ": 
            {
                date.setDate(date.getDate() + number * 7);
                return date;
                break;
            }
        case "d ": 
            {
                date.setDate(date.getDate() + number);
                return date;
                break;
            }
        case "h ": 
            {
                date.setHours(date.getHours() + number);
                return date;
                break;
            }
        case "m ": 
            {
                date.setMinutes(date.getMinutes() + number);
                return date;
                break;
            }
        case "s ": 
            {
                date.setSeconds(date.getSeconds() + number);
                return date;
                break;
            }
        default: 
            {
                date.setDate(date.getDate() + number);
                return date;
                break;
            }
    }
}







function onTextChange() {


    var arrival_date = new Date();
    var departure_date = new Date();

    var arrival_date_2 = $('#arrival_date').val().split("/");
    var departure_date_2 = $('#departure_date').val().split("/");

    arrival_date.setFullYear(parseInt10(arrival_date_2[2]), parseInt10(arrival_date_2[1]) - 1, parseInt10(arrival_date_2[0]));
    departure_date.setFullYear(parseInt10(departure_date_2[2]), parseInt10(departure_date_2[1]) - 1, parseInt10(departure_date_2[0]));

    if (arrival_date >= departure_date) {

        departure_date = (DateAdd("d", 1, arrival_date));
        var today = new Date();
        if (departure_date < today) {
            departure_date = new Date();
        }
        document.getElementById("departure_date").value = departure_date.format("dd/MM/yyyy");

    }
}

function onDDateChange() {

    var arrival_date = new Date();
    var departure_date = new Date();

    var arrival_date_2 = $('#arrival_date').val().split("/");
    var departure_date_2 = $('#departure_date').val().split("/");

    arrival_date.setFullYear(parseInt10(arrival_date_2[2]), parseInt10(arrival_date_2[1]) - 1, parseInt10(arrival_date_2[0]));
    departure_date.setFullYear(parseInt10(departure_date_2[2]), parseInt10(departure_date_2[1]) - 1, parseInt10(departure_date_2[0]));

    if (departure_date <= arrival_date) {



        arrival_date = (DateAdd("d", -1, departure_date));
        var today = new Date();
        if (arrival_date < today) {
            arrival_date = new Date();
        }
        document.getElementById("arrival_date").value = arrival_date.format("dd/MM/yyyy");


        onTextChange();
    }
}
