function trim(str) { 
    return str.replace(/(^\s*)|(\s*$)/g,"");
}

function checkAll(fieldName) {
    var box = document.getElementsByName(fieldName);
    for(i=0;i < box.length; i++) {
        box[i].checked = true;
    }
}

function unCheckAll(fieldName) {
    var box = document.getElementsByName(fieldName);
    for(i=0;i < box.length; i++) {
        box[i].checked = false;
    }
}

function phoneCheck(str) {
    var result = true;
    for (i=0; i<str.length; i++) {
        if (str.substr(i,1) < "0" || str.substr(i,1) > "9") {
			return false;
		}
    }
    return result;
}

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;
}

function genDate(yearID,monthID,dayID) {
    var dateset1 = new Array(31,29,31,30,31,30,31,31,30,31,30,31)
    var dateset2 = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
    var remonth = document.getElementById(monthID).selectedIndex

    if ((document.getElementById(yearID).value % 4) == 0)
        document.getElementById(dayID).options.length = dateset1[remonth];
    else
        document.getElementById(dayID).options.length = dateset2[remonth];
	
    for(i=1;i<=document.getElementById(dayID).options.length;i++){
        document.getElementById(dayID).options[i-1].text = i;
        document.getElementById(dayID).options[i-1].value = i;
    }
}

function numOnly(str) {
    var output = "";
    for (i=0; i<str.value.length; i++) {
        if (str.value.substr(i,1) >= "0" && str.value.substr(i,1) <= "9") {
            output += str.value.substr(i,1);
        }
    }
    str.value = output;
}

function handleEnter (functionName, event) {	
    if (event.keyCode == 13) {
        eval(functionName);
        return false;
    } else {
        return true;
    }
}

function stopRKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="password"))) {
        return false;
    }
}

function checkCheckBox(checkBoxName) {
    var boxcheck = false;
    var itemID = document.getElementsByName(checkBoxName);

    for(i=0; i<itemID.length; i++){
        if(itemID[i].checked){
            boxcheck = true;
            break;
        }
    }
    return boxcheck;
}

function openNoMenuWindow(page,pageName,width,height) {
    window.open(page, pageName, 'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=yes,resizable=yes,width='+width+',height='+height);
} 

function rawurlencode (str) {
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };

    var ret = '',unreserved = /[\w.~-]/;
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        } else {
            var code = str.charCodeAt(i);
            
            if (code < 128) { 
                ret += hexStr(code);
            } else if (code >= 128 && code < 2048) { 
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            } else if (code >= 2048 && code < 65536) { 
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            } else if (code >= 65536) { 
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function printPartOfInfo(partData) {
	
    var iframe =document.createElement('iframe');
    iframe.width=0;
    iframe.height=0;
    document.body.appendChild(iframe);

    if(iframe) {
	
        var ifWin = iframe.contentWindow || iframe;
        ifWin.document.open();
        ifWin.document.write(partData);
        ifWin.document.close();
        ifWin.focus();
        ifWin.print();
    }
    iframe.parentNode.removeChild(iframe);
}

function replaceString(str,currentWord,replaceWord) {
	
    var intIndexOfMatch = str.indexOf(currentWord);

    while (intIndexOfMatch != -1){
	
        str = str.replace(currentWord,replaceWord)
        intIndexOfMatch = str.indexOf(currentWord);
    }
    return str;
}

function resize(left_id, right_id) {    
    var left_col=($("#"+left_id).height());
    var right_col=($("#"+right_id).height());
	
    if(left_col > right_col) {
        $("#"+right_id).height($("#"+left_id).height());
    } else if(right_col > left_col) {
        $("#"+left_id).height($("#"+right_id).height());
    }
}

function checkForm(data){
	
    /*
	// Sample of using the checking 
	$('#reg_member').submit( function (){	
		var data = {
			emptyField : ['username', 'password', 'password2', 'name', 'email'],
			sameField : [['password', 'password2']],
			selectField : ['news_letter_choice', 'buy_heath'] // put class in here
			atLeast : [{ number: 2, elements: [] }]
		}
		return (anglia.checkForm(data) && anglia.member.username);
	});
 */
	
    var emptyChecking = data.emptyField || null;
    var sameFieldChecking = data.sameField || null;
    var selectFieldChecking = data.selectField || null;
    var atLeastChecking = data.atLeast || null;
    var warningFieldColor = '#fff0f0';
    var correctFieldColor = '#ffffff';
	
    var forCheckMail = true;
    var formBoo = true;
	
    var re_left_space = /^\s+/;
    var re_email = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    var re_no_space = /^[a-z]([0-9a-z_])+$/i;
	
    $('.compulsory').prev().css({
        'background-color':correctFieldColor
    });
	
    // Empty field validation
    if(emptyChecking != null){
        for(var i = 0; i < emptyChecking.length; i++){
			
            var thisboo = true;
            var el = $('#' + emptyChecking[i]);
            var g = el.val();
			
            if(g.length == 0){
                thisboo = false;
            } else 	if(el.hasClass('chk_mail')){
                if(!re_email.test(g)) thisboo = false;
            } else 	if(el.hasClass('no_space')){
                if(!re_no_space.test(g)) thisboo = false;
            }
			
            if(thisboo == false){
                el.css('background-color', warningFieldColor);
                formBoo = false;
            }
        }
    }
    // password form checking
    if(sameFieldChecking != null){
		
        for(var i = 0; i < sameFieldChecking.length; i++){
            var cur_chk_array = sameFieldChecking[i];
            var a = trim($('#'+cur_chk_array[0]).val());
            var b = trim($('#'+cur_chk_array[1]).val());
            if( a != '' ||  b != ''){
                if(	a != b ){
                    $('#' + cur_chk_array[1]).css('background-color', warningFieldColor);
                    formBoo = false;
                }
            }
        }
    }

    if(selectFieldChecking != null){
        for(var i = 0; i < selectFieldChecking.length; i ++ ){
            var elements = $('.'+selectFieldChecking[i]);
            if(!elements.is(':checked')) {
                $('.'+selectFieldChecking[i]+':first').before(errorDiv);
            }
        }
    }
	
    if(atLeastChecking != null){
		
        var atLeastPartBool = true;
	
        for(var i = 0; i < atLeastChecking.length; i++){
            var chkObj = atLeastChecking[i];
            var chkElements = chkObj.elements;
            var number = chkObj.number;
			
            if(chkElements.length == 0) continue;
			
            var isOk_num = 0;
            for(var g = 0 ; g < chkElements.length ; g++){
                var _boo = true;
                var _el = $('#' + chkElements[g]);
				
                if(_el.val() == ''){
                    _boo = false;
                }

                if(_boo){
                    isOk_num++;
                }
            }
			
            if(isOk_num < number){
                atLeastPartBool = false;
                for(var f = 0 ; f < chkElements.length ; f++){
                    var _boo = true;
                    var _el = $('#' + chkElements[f]);
                    if(_el.val() != ''){
                        _boo = false;
                    }
					
                    if(_boo){
                        _el.css('background-color', warningFieldColor);
                        break;
                    }
                }
            }
        }
    }
	
    $('.chk_mail').each(function(){
        if($(this).val() != ''){
            if(!re_email.test($(this).val())) {
                forCheckMail = false;
                if($(this).css('background-color') != warningFieldColor)
                    $(this).css('background-color', warningFieldColor);
            }
        }
    });
	
    formBoo = formBoo && atLeastPartBool && forCheckMail;
	
    return formBoo;
}

/* Jquery plugin of image swap
 *
 * This function must use with img.php
 * $('small-img-class').ImageSwaper('Big-img-Class');
 *
 */
(function($) {
    $.fn.ImageSwaper = function(bigClass,options){
        var opts = $.extend({}, $.fn.ImageSwaper.defaults, options);
        init($(this));
        $(this).mouseover(function(){
            $small=$(this);
            $big=$('.'+bigClass);
            $replaceFile=$small.attr('src').match(/file=([\w|\W]*)/)[0];
            $newpath=$big.attr('src').replace(/file=([\w|\W]*)/,$replaceFile);
            if($big.parent()[0].tagName=='A'&&$small.parent()[0].tagName=='A'){
                $big.parent().attr('href',$small.parent().attr('href'));
            }
            $big.attr('src',$newpath);
        });

        function init($small){
            $big=$('.'+bigClass);
            $small.each(function(){
                $small=$(this);
                if($small.parent()[0].tagName!='A'&&opts.generatelightBox){
                    $replaceFile=$small.attr('src').match(/file=([\w|\W]*)/)[0];
                    var link=document.createElement('a');
                    $(link).addClass(opts.lightClass);
                    $(link).attr('href',$replaceFile.replace('file=',''));
                    if(opts.groupImg){
                        $(link).attr(opts.groupAttr,opts.groupValue);
                    }
                    $small.wrap($(link));
                }
            });
            if($big.parent()[0].tagName!='A'&&opts.generatelightBox){
                var Big_link=$('<a>').addClass(opts.lightClass);
                $replaceFile=$big.attr('src').match(/file=([\w|\W]*)/)[0];
                Big_link.attr('href',$replaceFile.replace('file=',''));
                $big.wrap($(Big_link));
            }
            $("."+opts.lightClass).colorbox();
        }
    };

    $.fn.ImageSwaper.defaults={
        generatelightBox:true,
        lightClass:'colorbox',
        groupImg:true,
        groupAttr:'rel',
        groupValue:'group'
    };
})(jQuery);

/* Jquery plugin of image swap 2
 *
 * This function must use with img.php
 * $('small-img-class').AngliaImageSwaper();
 *
 */

(function($) {
    $.fn.AngliaImageSwaper = function(options){
        var opts = $.extend({}, $.fn.AngliaImageSwaper.defaults, options);
        var image_List=new Array();
        var i=0;
        var current_id=0;
        var big;
        var small_list=$(this);
        $(window).load(function(){
            init();
            setStyle();
        });

        function init(){
            if(!opts.big_place){
                big_div=$('<div>').attr('id','anglia-image-show-place').css('position','relative');
                small_list.before(big_div);
                big=$('#anglia-image-show-place');
            }else{
                big=$(opts.big_place).css('position','relative');
            }
            small_list.find('img').each(function(){
                $(this).addClass('anglia-image-swaper-unselected');
                $aTag=$('<a>').attr({
                    'href':"#",
                    'ref':i,
                    'class':'anglia-image-change'
                });
                $(this).attr("ref",i).css({
                    "width":opts.small_w,
                    "height":opts.small_h
                    }).wrap($aTag);
                $(this).attr('src',checkSrc($(this).attr('src'),opts.small_w,opts.small_h));
                image_List[i]=$(this);
                i++;
            });

            if(image_List.length>0){
                $big_image=$('<img>').attr({
                    "src":checkSrc(image_List[0].attr('src'),opts.big_w,opts.big_h),
                    'class':'anglia-big-image'
                }).css({
                    'width':opts.big_w,
                    'height':opts.big_h
                    });
                if(jQuery.trim(image_List[0].attr('alt'))!=''){
                    $big_image.attr({
                        "alt":image_List[0].attr('alt')
                        });
                }else{
                    $big_image.attr({
                        "alt":''
                    });
                }

                big.append($big_image).css({
                    'width':opts.big_w,
                    'height':opts.big_h
                    });
                image_List[0].removeClass('anglia-image-swaper-unselected');
                setTitle();
                $('.anglia-image-change').die({
                    'click':mouseClick,
                    'mouseenter':imgHoverEnter,
                    'mouseleave':ImgHoverLeave
                });
                $('.anglia-image-change').live({
                    'click':mouseClick,
                    'mouseenter':imgHoverEnter,
                    'mouseleave':ImgHoverLeave
                });
            }
        }

        function checkSrc(src,width,height){
            if(src.match('img.php')){
                if(src.match(/width=([0-9]*)/)){
                    src=src.replace(/width=([0-9]*)/,'width='+width);
                }else{
                    src+='&width='+width;
                }
                if(src.match(/height=([0-9]*)/)){
                    src=src.replace(/height=([0-9]*)/,'height='+height);
                }else{
                    src+='&height='+height;
                }
            }
            return src;
        }

        function mouseClick(){
            var id=$(this).attr('ref');
            current_id=id;
            removeTitle();
            $('.anglia-image-change').die({
                'click':mouseClick/*,
                'mouseenter':imgHoverEnter,
                'mouseleave':ImgHoverLeave*/
            });
            $('.anglia-image-change').live('click',function(){return false;});
            small_list.find('img').each(function(){
                if($(this).attr('ref')!=current_id){
                    $(this).animate({
                        opacity: opts.opacity_radio
                    });
                }else{
                    $(this).animate({
                        opacity: 1
                    });
                }
            });
            $('.anglia-big-image').fadeOut(opts.speed,function(){
                if(jQuery.trim(image_List[id].attr('alt'))!=''){
                    $(this).attr({
                        'alt':image_List[id].attr('alt')
                        });
                }else{
                    $(this).attr({
                        'alt':''
                    });
                }
                $(this).attr({
                    'src':checkSrc(image_List[id].attr('src'),opts.big_w,opts.big_h)
                    }).fadeIn(opts.speed,function(){
                    setTitle();
                    $('.anglia-image-change').live({
                        'click':mouseClick/*,
                        'mouseenter':imgHoverEnter,
                        'mouseleave':ImgHoverLeave*/
                    });
                });
            });

            return false;
        }

        function imgHoverEnter(){
            $(this).find('img').stop(true,true).animate({
                opacity: 1
            });
        }

        function ImgHoverLeave(){
            if($(this).find('img').attr('ref')!=current_id){
                $(this).find('img').stop(true,true).animate({
                    opacity: opts.opacity_radio
                });
            }
        }

        function setStyle(){
            $('.anglia-image-swaper-unselected').css({
                'opacity':opts.opacity_radio,
                'filter':'alpha(opacity='+(opts.opacity_radio*100)+')'
            });
        }

        function setTitle(){
            if(jQuery.trim($('.anglia-big-image').attr('alt'))!=''){
                title=$('<div>').attr('id','anglia-image-title')
                .css({
                    'width':opts.big_w,
                    'position':'absolute',
                    'left':0,
                    'bottom':0,
                    'background':opts.title_bg,
                    'color':opts.title_font,
                    'opacity':opts.opacity_radio_title,
                    'filter':'alpha(opacity='+(opts.opacity_radio_title*100)+')'
                })
                .append('<h3 style="opacity:1; filter:alpha(opacity=100); color:'+opts.title_font+'">'+$('.anglia-big-image').attr('alt')+'</h3>');
                $('.anglia-big-image').after(title);
            }
        }

        function removeTitle(){
            if($('#anglia-image-title')){
                $('#anglia-image-title').fadeOut(200,function(){
                    $(this).remove();
                });
            }
        }
    };

    $.fn.AngliaImageSwaper.defaults={
        big_w:500,
        big_h:500,
        small_w:150,
        small_h:150,
        speed:1000,
        big_place:false,
        title_bg:'#fff',
        title_font:'#000000',
        opacity_radio:0.4,
        opacity_radio_title:0.6
    };
})(jQuery);

/*  Function about url info
 *
 *  This function get all parameters and url info
 *
 *  protocol:Http Or Https
 *  url: Full path
 *  domain: domain name e.g. www.anglia.com.hk
 *  folder: Array list of folder
 *  file: Name of file e.g. index.php
 *  getValue: Object list of parameters which are begin of & or ?
 *  ajaxValue: Object list of parameters which are begin of #
 *
 **/

var urlInfo={
    url:'',
    path:'',
    protocol:'',
    file:'',
    domain:'',
    folder:new Array(),
    getValue:new Object(),
    ajaxValue:new Object(),
    init:function(){
        url=document.location.href;
        this.getAllAttr();
    },
    getAllAttr:function(){
        getAttr=url.split('?');
        this.path=getAttr[0];
        this.getLinkInfo();
        this.getLinkValue(url);
        this.getAjaxValue(url);
    },
    getLinkInfo:function(){
        info=this.path.split('://');
        this.protocol=info[0];
        eachFolder=info[info.length-1].split('/');
        this.file=eachFolder[eachFolder.length-1];
        this.domain=eachFolder[0];
        for(k=1;k<eachFolder.length-1;k++){
            this.folder[k-1]=eachFolder[k];
        }
    },
    getLinkValue:function(getAttr){
        attr=getAttr.match(/(&[\w]*=[\w]*)|(\?[\w]*=[\w]*)/g);
        for(key in attr){
            this.setAttr(attr[key], this.getValue);
        }
    },
    getAjaxValue:function(ajaxAttr){
        attr=ajaxAttr.match(/(#[\w]*=[\w]*)/g);
        for(key2 in attr){
            this.setAttr(attr[key2], this.ajaxValue);
        }
    },
    setAttr:function(str,arr){
        if(jQuery.trim(str)!=''){
            str=str.replace(/#|&|\?/,'');
            temp=str.split('=');
            arr[temp[0]]=temp[1];
        }
    }
}

