﻿//该脚本库主要用于各频道间的公共代码

/*zhang.hx 2011-06-07 定义佰程各频道JS命名空间，更便于方法的重用和管理*/
if (typeof Byecity == "undefined" || !Byecity) {
    var Byecity = {};
}
Byecity.Common = new Object();
Byecity.Free = new Object();
Byecity.Member = new Object();
Byecity.Pay = new Object();
Byecity.Visa = new Object();
Byecity.Hotel = new Object();
Byecity.Crusise = new Object();
Byecity.Group = new Object();
Byecity.All = new Object();



//扩展JS原类型
Object.extendFn = function(target, sourceArray) {
    for (var property in sourceArray) {
        try {
            switch (property.toString()) {
                case "fromElement":
                case "toElement":
                case "x":
                case "y":
                case "offsetX":
                case "offsetY":
                case "srcElement":
                case "returnValue":
                    continue;
                    break;
                default:
                    target[property] = sourceArray[property];
                    break;
            }
        }
        catch (exx)
        { }
    }
    return target;
}

//扩展String
Object.extendFn(String.prototype, {
    trim: function() {//清除左右端空格        
        return this.replace(/(^\s*)|(\s*$)/g, "");
    },
    ltrim: function() {//清除左端空格        
        return this.replace(/(^\s*)/g, "");
    },
    rtrim: function() {//清除右端空格        
        return this.replace(/(\s*$)/g, "");
    },
    clearHTML: function() {//清除html标签        
        return this.replace(/<[^>]*>/g, "");
    },
    lower: function() {//转为小写        
        return this.toLowerCase();
    },
    upper: function() {//转为大写
        return this.toUpperCase();
    },
    reallength: function() {//实际长度每个中文占两位
        return this.replace(/[^\u4e00-\u9fa5\uf900-\ufa2d]/, "**").length;
    },
    isChn: function() {//是否全为中文
        if (/^([\u4e00-\u9fa5\uf900-\ufa2d])*$/.test(this))
            return true;
        else
            return false;
    },
    hasChn: function() {//是否包含中文
        if (/[\u4e00-\u9fa5\uf900-\ufa2d]/.test(this))
            return true;
        else
            return false;
    },
    dbc2sbc: function() {//全角转半角
        var result = '', code = '';
        for (var i = 0; i < this.length; i++) {
            code = this.charCodeAt(i); //获取当前字符的unicode编码   
            if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
                result += String.fromCharCode(this.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
            else if (code == 12288)//空格
                result += String.fromCharCode(this.charCodeAt(i) - 12288 + 32);
            else
                result += this.charAt(i);
        }
        return result;
    },
    format: function() {//参数格式化，如 "abc{0}efg{1}ijk".format("d","h") -> "abcdefghijk"        
        var args = arguments;
        return this.replace(/\{(\d+)\}/g, function(m, i) {
            return args[i];
        });
    },
    append: function(str, before) {
        //向当前字符串追加字符串,如:
        //"abc".append( "def" ) -> "abcdef";
        //"abc".append( "def",true ) -> "defabc";
        if (before != null && before)
            return str.toString() + this;
        return this + str.toString();
    },
    appendFormat: function() {//串追参数格式化字符串，如:"abc".appendFormat("defg{0}ijk","h") -> "abcdefghijk"
        var fstr = arguments[0];
        var arr = $$.array(arguments);
        var args = arr.select(function(item, index) {
            return index != 0;
        });
        fstr = fstr.replace(/\{(\d+)\}/g, function(m, i) {
            return args[i];
        });
        return this + fstr;
    },
    startWith: function(str) {//是否以指定字符起始
        if (str == null || str == "" || this.length == 0 || str.length > this.length)
            return false;
        if (this.substr(0, str.length) == str)
            return true;
        else
            return false;
        return true;
    },
    endWith: function(str) {//是否以指定字符结束
        if (str == null || str == "" || this.length == 0 || str.length > this.length)
            return false;
        if (this.substring(this.length - str.length) == str)
            return true;
        else
            return false;
        return true;
    },
    isNOrE: function() {//空对象或长度为0
        return (this == null) || (this.length == 0)
    },
    isN: function() {//是否数字
        return checkFn.isN(this);
    },
    isNN: function() {//是否正整数
        return checkFn.isNN(this);
    },
    is_NN: function() {//是否负整数
        return checkFn.is_NN(this);
    },
    isUserName: function() {//是否用户名格式
        return checkFn.isUserName(this);
    },
    isEmail: function() {//是否邮箱
        return checkFn.isEmail(this);
    },
    isMobile: function() {//是否手机号
        return checkFn.isMobile(this);
    },
    isTel: function() {//是否固定电话
        return checkFn.isTel(this);
    },
    isIDCard: function() {//是否身份证,非严格判断
        return checkFn.isIDCard(this);
    },
    toInt: function() {//转为Int
        try { return parseInt(this); }
        catch (e) { return 0; }
    },
    toDate: function() {//字符串转为Date
        var DateStr = this;
        if (!checkFn.isLDate(DateStr) && !checkFn.isSDate(DateStr))//两种都不满足
            return null;

        var converted = Date.parse(DateStr);
        var myDate = new Date(converted);
        if (isNaN(myDate)) {
            if (checkFn.isSDate(DateStr)) {
                //2008-01-01
                var arys = DateStr.split('-');
                myDate = new Date(arys[0], --arys[1], arys[2]);
            }
            else {
                //2008-01-01 00:00:00
                var partArray = DateStr.split(" ");
                var darray = partArray[0].split("-");
                var tarray = partArray[1].split(":");
                myDate = new Date(darray[0], --darray[1], darray[2], tarray[0], tarray[1], tarray[2]);
            }
        }
        return myDate;
    },
    isDateTime: function() {//是否日期时间//2008-01-01 00:00:00
        return checkFn.isLDate(this)
    },
    isDate: function() {//是否短日期//2008-01-01
        return checkFn.isSDate(this);
    },
    isTime: function() {//是否时间//00:00:00
        return checkFn.isTime(this);
    },
    times: function(n) {//重复当前字符串n次
        var result = '';
        for (var i = 0; i < n; i++)
            result += this;
        return result;
    },
    padl: function(c, len) {//以c补左，如 "2".padl("0",5) -> 00002
        if (this.length >= len)
            return this;
        var n = len - this.length;
        return c.toString().times(n) + this;
    },
    padr: function(c, len) {//以c补右，如 "2".padr("0",5) -> 20000
        if (this.length >= len)
            return this;
        var n = len - this.length;
        return this + c.toString().times(n);
    },
    capitalize: function() { //第一个字符转换为大写
        return this.charAt(0).upper() + this.substring(1).lower();
    },
    sub: function(len, start, end) {
        if (len == null) return this;
        if (start == null) start = 0;
        if (end == null || (end + 1) > this.length) end = this.length;
        var a = 0, i = 0, temp = "";
        for (i = start; i < end; i++) { a += this.charCodeAt(i) > 255 ? 2 : 1; if (a > len) return temp; temp += this.charAt(i); }
        return temp;
    }
});

//扩展Date
Object.extendFn(Date.prototype, {
    datePart: function() {//获取日期部分
        return this.format("yyyy-MM-dd");
    },
    timePart: function() {//获取时间部分
        return this.format("HH:mm:ss");
    },
    isLeapYear: function() {//判断闰年
        return (0 == this.getYear() % 4 && ((this.getYear() % 100 != 0) || (this.getYear() % 400 == 0)));
    },
    format: function(formatStr) {//日期格式化,如：(new Date()).format("yyyy-MM-dd HH:mm:ss")
        var str = formatStr;
        var Week = ['日', '一', '二', '三', '四', '五', '六'];
        str = str.replace(/yyyy|YYYY/, this.getFullYear());
        str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

        str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
        str = str.replace(/M/g, (this.getMonth() + 1));

        str = str.replace(/w|W/g, Week[this.getDay()]);

        str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
        str = str.replace(/d|D/g, this.getDate());

        str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
        str = str.replace(/h|H/g, this.getHours());
        str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
        str = str.replace(/m/g, this.getMinutes());

        str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
        str = str.replace(/s|S/g, this.getSeconds());

        return str;
    },
    daysDiff: function(targetDate) {//天数差,如：//new Date() = 2008-10-21, (new Date()).daysDiff("2008-10-20") -> 1 注意：targetDate必须格式化成：yyyy-MM-dd的字符串
        var thisDate = this.format("yyyy-MM-dd");
        var thisMonth = thisDate.substring(5, thisDate.lastIndexOf('-'));
        var thisDay = thisDate.substring(thisDate.length, thisDate.lastIndexOf('-') + 1);
        var thisYear = thisDate.substring(0, thisDate.indexOf('-'));

        var targetMonth = targetDate.substring(5, targetDate.lastIndexOf('-'));
        var targetDay = targetDate.substring(targetDate.length, targetDate.lastIndexOf('-') + 1);
        var targetYear = targetDate.substring(0, targetDate.indexOf('-'));

        var cha = ((Date.parse(thisMonth + '/' + thisDay + '/' + thisYear) - Date.parse(targetMonth + '/' + targetDay + '/' + targetYear)) / 86400000);
        return Math.abs(cha);
    },
    dateDiff: function(datePart, dtEnd) {//时间差
        //datePart : 比较的部分
        //dtEnd 比较的时间
        var dtStart = this;
        dtEnd = dtEnd.toDate();
        switch (datePart.lower()) {
            case 's': //秒
                return parseInt((dtEnd - dtStart) / 1000);
            case 'n': //分
                return parseInt((dtEnd - dtStart) / 60000);
            case 'h': //时
                return parseInt((dtEnd - dtStart) / 3600000);
            case 'd': //天
                return parseInt((dtEnd - dtStart) / 86400000);
            case 'day': //天
                return parseInt((dtEnd - dtStart) / 86400000);
            case 'w': //周
                return parseInt((dtEnd - dtStart) / (86400000 * 7));
            case 'm': //月
                return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
            case 'y': //年
                return dtEnd.getFullYear() - dtStart.getFullYear();
        }
    },
    dateAdd: function(datePart, Number) {
        var dtTmp = this;
        var date;
        switch (datePart) {
            case 's':
                date = new Date(Date.parse(dtTmp) + (1000 * Number));
                break;
            case 'mi':
                date = new Date(Date.parse(dtTmp) + (60000 * Number));
                break;
            case 'h':
                date = new Date(Date.parse(dtTmp) + (3600000 * Number));
                break;
            case 'd':
                date = new Date(Date.parse(dtTmp) + (86400000 * Number));
                break;
            case 'day':
                date = new Date(Date.parse(dtTmp) + (86400000 * Number));
                break;
            case 'w':
                date = new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
                break;
            case 'mon':
                date = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;
            case 'y':
                date = new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;
        }
        return date.format("yyyy-MM-dd HH:mm:ss").toDate();
    },
    dayOfYear: function() {//一年中的第几天
        //当前date   
        var now = this;
        //每月多少日   
        var monthOfFullDay = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        //当前日，在本年中第几日   
        var currentDayOfYear = 0;
        //是否为润年，即能被4整除   
        var isFullYear = false;
        var currentDayOfWeekIsLastDay = false;
        var firstDayOfYearIsFirstDayOfWeek = false;
        //当前年份   
        var year = 0;
        if (now.getYear() >= 2000)
            year = now.getYear();
        else
            year = now.getYear() + 1900;
        //当前月份   
        var month = now.getMonth();
        //当前日   
        var day = now.getDate();
        //当前星期几   
        var week = now.getDay();
        //为闰年，设isFullYear为true   
        if (year % 4 == 0) {
            isFullYear = true;
        }
        //循环计算天数   
        for (var i = 0; i < monthOfFullDay.length; i++) {
            //判断数组月份是否小于等于当前月份   
            if (i < month) {
                //是闰年和2月份   
                if (isFullYear && i == 1)
                    currentDayOfYear = currentDayOfYear + 29;
                else
                    currentDayOfYear = currentDayOfYear + monthOfFullDay[i];
            }
            if (i == month)
                currentDayOfYear = currentDayOfYear + day;
        }

        //设置本年1月1日   
        var firstDayOfYear = new Date();
        firstDayOfYear.setYear(year);
        firstDayOfYear.setMonth(0);
        firstDayOfYear.setDate(1);

        if (firstDayOfYear.getDay() == 0)
            firstDayOfYearIsFirstDayOfWeek = true;

        var weeksOfYear = currentDayOfYear;

        //本星期是否为最后一日，否，则减去本兴起所有日   
        if (!currentDayOfWeekIsLastDay)
            weeksOfYear = weeksOfYear + firstDayOfYear.getDay();

        //是否第一个星期为第一日（即星期日），否，则减去本星期所有日   
        if (!firstDayOfYearIsFirstDayOfWeek)
            weeksOfYear = weeksOfYear + (7 - week - 1);

        return weeksOfYear;
    },
    weekOfYear: function() {//年的第几周
        var day = this.dayOfYear();
        return day / 7;
    },
    dayOfWeek: function() {//周的第几天
        return this.getDay();
    },
    dayOfWeekCn: function() {//星期，中文
        return ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][this.getDay()];
    },
    dayOfWeekEn: function() {//星期，英文
        return ["SUNDAY", "MONDAY", "TURESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"][this.getDay()];
    }
});



var checkFn = {
    //数字
    isN: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        if (/^(\-|\+)?(\d+)*$/.test(str))
            return true;
        return false;
    },
    //正整数
    isNN: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        if (/^(((\+)?[1-9]+(\d*))|(([1-9])+(\d*)))$/.test(str)) // 例: +10 或 10
            return true;
        return false;
    },
    //负整数
    is_NN: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        if (/^(\-){1}(\d+)*$/.test(str))
            return true;
        return false;
    },
    //验证用户名
    isUserName: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        //非数字开头，字母数字下划线，6~18位
        if (/^[A-Za-z_]{1}[A-Za-z0-9_]{5,17}$/.test(str))
            return true;
        return false;
    },
    //邮箱
    isEmail: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        var reg = /^([a-zA-Z0-9_-])+(\.*)([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        return reg.test(str);
    },
    //手机号
    isMobile: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        if (/^1[0-9]{10}$/.test(str))
            return true;
        return false
    },
    //固定电话
    isTel: function(str) {
        if (str == null)
            return false;
        str = str.trim();
        //3~4位区号-7~8位电话号码
        if (/^(\d{3,4})-(\d{7,8})/.test(str))
            return true;
        return false;
    },
    //身份证,非严格判断
    isIDCard: function(str) {
        if (/^(\d{18}|\d{15}|\d{14}[A-Za-z]{1})$/.test(str))
            return true;
        return false;
    },
    //日期+时间
    isLDate: function(str) {
        if (/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[0-9])|([1][0-9])|([2][0-4]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/.test(str.trim()))
            return true;
        return false;
    },
    //日期
    isSDate: function(str) {
        if (/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))$/.test(str.trim()))
            return true;
        return false;
    },
    //时间,有点失灵
    isTime: function(str) {
        if (/^(\s(((0?[0-9])|([1][0-9])|([2][0-4]))\:([0-5]?[0-9])((\s)|(\:([0-5]?[0-9])))))?$/.test(str.trim()));
        return true;
        return false;
    }
}




/**
jQuery.url
https://github.com/allmarkedup/jQuery-URL-Parser
*/
//jQuery.url = function() { var segments = {}; var parsed = {}; var options = { url: window.location.href.toLowerCase(), strictMode: false, key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q: { name: "queryKey", parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/} }; var parseUri = function() { str = decodeURI(options.url); var m = options.parser[options.strictMode ? "strict" : "loose"].exec(str); var uri = {}; var i = 14; while (i--) { uri[options.key[i]] = m[i] || "" } uri[options.q.name] = {}; uri[options.key[12]].replace(options.q.parser, function($0, $1, $2) { if ($1) { uri[options.q.name][$1] = $2 } }); return uri }; var key = function(key) { if (!parsed.length) { setUp() } if (key == "base") { if (parsed.port !== null && parsed.port !== "") { return parsed.protocol + "://" + parsed.host + ":" + parsed.port + "/" } else { return parsed.protocol + "://" + parsed.host + "/" } } return (parsed[key] === "") ? null : parsed[key] }; var param = function(item) { if (!parsed.length) { setUp() } return (parsed.queryKey[item] === null) ? null : parsed.queryKey[item] }; var setUp = function() { parsed = parseUri(); getSegments() }; var getSegments = function() { var p = parsed.path; segments = []; segments = parsed.path.length == 1 ? {} : (p.charAt(p.length - 1) == "/" ? p.substring(1, p.length - 1) : path = p.substring(1)).split("/") }; return { setMode: function(mode) { strictMode = mode == "strict" ? true : false; return this }, setUrl: function(newUri) { options.url = newUri === undefined ? window.location : newUri; setUp(); return this }, segment: function(pos) { if (!parsed.length) { setUp() } if (pos === undefined) { return segments.length } return (segments[pos] === "" || segments[pos] === undefined) ? null : segments[pos] }, attr: key, param: param} } ();
// JQuery URL Parser plugin - https://github.com/allmarkedup/jQuery-URL-Parser
// Written by Mark Perkins, mark@allmarkedup.com
// License: http://unlicense.org/ (i.e. do what you want with it!)

; (function($, undefined) {

    var tag2attr = {
        a: 'href',
        img: 'src',
        form: 'action',
        base: 'href',
        script: 'src',
        iframe: 'src',
        link: 'href'
    },

	key = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "fragment"], // keys available to query

	aliases = { "anchor": "fragment" }, // aliases for backwards compatability

	parser = {
	    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
	    loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
	},

	querystring_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g, // supports both ampersand and semicolon-delimted query string key/value pairs

	fragment_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g; // supports both ampersand and semicolon-delimted fragment key/value pairs

    function parseUri(url, strictMode) {
        var str = decodeURI(url),
		    res = parser[strictMode || false ? "strict" : "loose"].exec(str),
		    uri = { attr: {}, param: {}, seg: {} },
		    i = 14;

        while (i--) {
            uri.attr[key[i]] = res[i] || "";
        }

        // build query and fragment parameters

        uri.param['query'] = {};
        uri.param['fragment'] = {};

        uri.attr['query'].replace(querystring_parser, function($0, $1, $2) {
            if ($1) {
                uri.param['query'][$1] = $2;
            }
        });

        uri.attr['fragment'].replace(fragment_parser, function($0, $1, $2) {
            if ($1) {
                uri.param['fragment'][$1] = $2;
            }
        });

        // split path and fragement into segments

        uri.seg['path'] = uri.attr.path.replace(/^\/+|\/+$/g, '').split('/');

        uri.seg['fragment'] = uri.attr.fragment.replace(/^\/+|\/+$/g, '').split('/');

        // compile a 'base' domain attribute

        uri.attr['base'] = uri.attr.host ? uri.attr.protocol + "://" + uri.attr.host + (uri.attr.port ? ":" + uri.attr.port : '') : '';

        return uri;
    };

    function getAttrName(elm) {
        var tn = elm.tagName;
        if (tn !== undefined) return tag2attr[tn.toLowerCase()];
        return tn;
    }

    $.fn.url = function(strictMode) {
        var url = '';

        if (this.length) {
            url = $(this).attr(getAttrName(this[0])) || '';
        }

        return $.url(url, strictMode);
    };

    $.url = function(url, strictMode) {
        if (arguments.length === 1 && url === true) {
            strictMode = true;
            url = undefined;
        }

        strictMode = strictMode || false;
        url = url || window.location.toString();

        return {

            data: parseUri(url, strictMode),

            // get various attributes from the URI
            attr: function(attr) {
                attr = aliases[attr] || attr;
                return attr !== undefined ? this.data.attr[attr] : this.data.attr;
            },

            // return query string parameters
            param: function(param) {
                return param !== undefined ? this.data.param.query[param] : this.data.param.query;
            },

            // return fragment parameters
            fparam: function(param) {
                return param !== undefined ? this.data.param.fragment[param] : this.data.param.fragment;
            },

            // return path segments
            segment: function(seg) {
                if (seg === undefined) {
                    return this.data.seg.path;
                }
                else {
                    seg = seg < 0 ? this.data.seg.path.length + seg : seg - 1; // negative segments count from the end
                    return this.data.seg.path[seg];
                }
            },

            // return fragment segments
            fsegment: function(seg) {
                if (seg === undefined) {
                    return this.data.seg.fragment;
                }
                else {
                    seg = seg < 0 ? this.data.seg.fragment.length + seg : seg - 1; // negative segments count from the end
                    return this.data.seg.fragment[seg];
                }
            }

        };

    };

})(jQuery);



/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};






















/*牛继占 2011-06-07 扩展公共类型对象*/
var HomePageHost = $("#hidHomePageHost").val();
if (HomePageHost == undefined) {
    HomePageHost = "http://www.byecity.com";
}



$(document).ready(function() {
    ////订单、用户来源跟踪代码
    //$.cookie("Byecity_utm_source", $.url().param("utm_source"), { path: "/", domain: "byecity.com" });
    //$.cookie("Byecity_utm_medium", $.url().param("utm_medium"), { path: "/", domain: "byecity.com" });
    //$.cookie("Byecity_utm_content", $.url().param("utm_content"), { path: "/", domain: "byecity.com" });
    //if ($.cookie("Byecity_referrer") == null || $.cookie("Byecity_referrer") == undefined || (document.referrer != null && document.referrer.indexOf("byecity.com") == -1)) {
    //    var Byecity_referrer = document.referrer;
    //    if (Byecity_referrer == "") {
    //        Byecity_referrer = document.location;
    //    }
    //    $.cookie("Byecity_referrer", Byecity_referrer, { path: "/", domain: "byecity.com" });
    //}
    $.cookie("Byecity_from", $.url().param("from"), { path: "/", domain: "byecity.com" });

    //静态页面加载头尾\非动态面并且不显示页面头尾
    if (document.URL.indexOf(".aspx") == -1 && document.URL.indexOf(".html") == -1 && document.URL.indexOf(".ashx") == -1 && document.URL.indexOf(".asmx") == -1) {
        var showhf = "utf.htm"; //默认显示头尾
        var hidhf = "0"; //默认显示
        if (!($.url().param("showhf") == undefined) && $.url().param("showhf") != null && $.url().param("showhf").length > 0) {
            showhf = $.url().param("showhf");
        }

        if (!($.url().param("hidhf") == undefined) && $.url().param("hidhf") != null && $.url().param("hidhf").length > 0) {
            hidhf = $.url().param("hidhf");
        }

        if (hidhf != 1 && ($("#jsTop").html() == undefined || $("#jsTop").html().indexOf("<") == -1)) {
            $.ajax({
                type: "GET",
                url: "Ajax/UserHandler.ashx",
                data: "method=gethead&hidhf={0}&showhf={1}".format(hidhf, showhf),
                async: false,
                success: function(data) {
                    $("#jsTop").html(data);
                }
            });
        }

        if (hidhf != 1 && ($("#jsBottom").html() == undefined || $("#jsBottom").html().indexOf("<") == -1)) {
            $.ajax({
                type: "GET",
                url: "Ajax/UserHandler.ashx",
                data: "method=getfoot&hidhf={0}&showhf={1}".format(hidhf, showhf),
                async: false,
                success: function(data) {
                    $("#jsBottom").html(data);
                }
            });
        }
        //根据相关参数再次处理头尾
        if (hidhf == 1) {
            $("#jsTop").hide();
            $("#jsBottom").hide();
        }
    }

    //根据URL参数处理页面内所有的链接 
    if ($.url().param("showhf") && !($.url().param("showhf") == undefined)) {
        $("a").each(function() {
            $(this).attr("href", DoWithShowhf($(this).attr("href")));
        });
    }

    //根据URL参数处理页面内所有的链接
    if ($.url().param("hidall") && !($.url().param("hidall") == undefined)) {
        $("a").each(function() {
        $(this).attr("href", DoWithHideAll($(this).attr("href")));
            $(this).attr("target", "_self");
        });
    }

    setNavgator(document.URL);

    //添加“加入收藏”代码
    $("#shoucang").click(function() {
        myAddPanel("佰程旅行网", "http://www.byecity.com", "佰程旅行网 您身边的旅行专家！提供出国旅游，自由行，旅游签证，国际酒店预订等全方位的出境旅游服务");
    }).hover(function() { $(this).css("text-decoration", "underline"); }, function() { $(this).css("text-decoration", "none"); });

    //处理线路图片列表及产品详情列表
    //alert($("#ByecityImagesList img").length); 
    $(".ByecityImagesList img").each(function(i, n) {
        DrawImage(this, 280, 320);
    });
    //alert($("#ByecityJourney img").length); 
    $(".ByecityJourney img").each(function(i, n) {
        DrawImage(this, 160, 160);
    });
});

function DoWithShowhf(href_old_string) {
    var href_old = $.url(href_old_string); //转换成URL对象
    var href_new = href_old_string; //默认情况下新旧URL一样
    if (!($.url().param("showhf") == undefined)) {//判断页面URL中是否含showhf参数
        if (!href_old.param("showhf") && href_old.param("showhf") == undefined) {//判断参数href_old_string里是否含showhf参数
            var query = href_old.attr("query");
            if (query && !(query == undefined)) {
                href_new = "{0}&showhf={1}".format(href_old.attr("source"), $.url().param("showhf"));
            }
            else {
                href_new = "{0}?showhf={1}".format(href_old.attr("source"), $.url().param("showhf"));
            }
        }
    }
    return href_new;
}

function DoWithHideAll(href_old_string) {
    var href_old = $.url(href_old_string); //转换成URL对象
    var href_new = href_old_string; //默认情况下新旧URL一样
    if (!($.url().param("hidall") == undefined)) {//判断页面URL中是否含hidall参数
        if ($.url().param("hidall") == 1) {
            if (!href_old.param("hidall") && href_old.param("hidall") == undefined) {//判断参数href_old_string里是否含hidall参数
                var query = href_old.attr("query");
                if (query && !(query == undefined)) {
                    href_new = "{0}&hidhf=1&hidall={1}".format(href_old.attr("source"), $.url().param("hidall"));
                }
                else {
                    href_new = "{0}?hidhf=1&hidall={1}".format(href_old.attr("source"), $.url().param("hidall"));
                }
            }
        }
    }
    return href_new;
}
//等比例缩放图片
function DrawImage(Img, width, height) {
    var image = new Image();
    image.src = Img.src;
    if (image.width > width || image.height > height) {
        w = image.width / width;
        h = image.height / height;
        if (w > h) {
            Img.width = width;
            Img.height = image.height / w;
        } else {
            Img.height = height;
            Img.width = image.width / h;
        }
    }
}

//添加收藏方法
function myAddPanel(title, url, desc) {
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function"))//Gecko
    {
        window.sidebar.addPanel(title, url, desc);
    }
    else//IE
    {
        window.external.AddFavorite(url, title);
    }
}
function setNavgator(url) {
    $(".nav a,.nav2_a a").each(function() {
        var href = $(this).attr("href");
        if (href == undefined) {
            href = "";
        }
        if (url.indexOf(href) == -1) {
            $(this).parent().parent("li").removeClass("hover");

            //对于巴士游线路进行特殊处理
            if (href == "http://group.byecity.com/bus/" && !(url.indexOf("http://bus.byecity.com") == -1)) {
                $(this).parent().parent("li").addClass("hover");
            }
        }
        else if (href.length > 0) {
            $(this).parent().parent("li").addClass("hover");
            if (document.URL.indexOf(".htm") != -1 && document.URL.indexOf(".html") == -1) {//以htm结尾，非html结尾 设置菜单没有选中项
                $(this).parent("li").removeClass("hover");
            }
            //判断“首页”和“参团游”的选项是否应该选中 
            if (href == "http://www.byecity.com/" && url != "http://www.byecity.com/") {
                $(this).parent().parent("li").removeClass("hover");
            }
            if (href == "http://group.byecity.com/" && url == "http://group.byecity.com/bus/") {
                $(this).parent().parent("li").removeClass("hover");
            }
        }
    });

}




function setTab(name, cursel, n) {
    for (i = 1; i <= n; i++) {
        var menu = document.getElementById(name + i);
        var con = document.getElementById("con_" + name + "_" + i);
        if (menu != null)
            menu.className = i == cursel ? "hover" : "";
        if (con != null)
            con.style.display = i == cursel ? "block" : "none";
    }
}

function setTab2(cursel) {
    for (i = 1; i <= 4; i++) {
        var menu = document.getElementById("search" + i);
        var con = document.getElementById("con_search_" + i);

        if (menu != null)
            menu.className = i == cursel ? "hover" : "";
        if (con != null) {
            if (window.navigator.userAgent.indexOf("MSIE") >= 1)
                con.style.display = i == cursel ? "block" : "none";
            else
                con.style.display = i == cursel ? "table" : "none";
        }

    }
    if (cursel == 5) {
        var arr = $("#freeDepartCity").val().split(',');
        var Obj = $("#departCityForFree")[0];
        Obj.options.length = 1;
        for (var i = 0; i < arr.length; i++) {
            Obj.options.add(new Option(arr[i].split('|')[1], arr[i].split('|')[0]));
        }
    }
    else if (cursel == 6) {
        var arr = $("#groupDepartCity").val().split(',');
        var Obj = $("#departCityForGroup")[0];
        Obj.options.length = 1;
        for (var i = 0; i < arr.length; i++) {
            Obj.options.add(new Option(arr[i].split('|')[1], arr[i].split('|')[1]));
        }
    }
}

////GA跟踪代码
//document.write('<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>');
//function analytics() {
//    _uacct = "UA-2626446-2"; //你的ID
//    urchinTracker();
//}
//if (document.all) {
//    window.attachEvent('onload', analytics);
//}
//else {
//    window.addEventListener('load', analytics, false);
//}

//function importJ(fpath) {
//    document.write('<script src="' + fpath + '"></script>');
//}

//合作效果分析代码





