;(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.regexp = {
		bg: /^url\(["']?(.*\.png([?].*)?)["']?\)$/i,
		img: /.*\.png([?].*)?$/i
	},
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/img/pixel.gif';
	};
	
	var hack = {
		base	: $('base').attr('href'),
		ltie7	: $.browser.msie && $.browser.version < 7,
		filter	: function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
		function fixImage(image, source, width, height, hidden) {
			image.css({filter:hack.filter(source), width: width, height: height})
			  .attr({src:$.ifixpng.getPixel()})
			  .positionFix();
		}
		
    	return this.each(function() {
			var $$ = $(this);
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				var source, img;
				if (this.src && this.src.match($.ifixpng.regexp.img)) { // make sure it is png image
					// use source tag value if set 
					source = (hack.base && this.src.substring(0,1)!='/' && this.src.indexOf(hack.base) === -1) ? hack.base + this.src : this.src;
					// If the width is not set, we have a problem; the image is not probably visible or not loaded
					// and we need a work around.
					if (!this.width || !this.height) {
						$(new Image()).one('load', function() {
							fixImage($$, source, this.width, this.height);
							$(this).remove();
						}).attr('src', source);
					// If the image already has dimensions (it's loaded and visible) we can fix it straight away.
					} else fixImage($$, source, this.width, this.height);
				}
			} else if (this.style) { // hack png css properties present inside css
				var imageSrc = $$.css('backgroundImage');
				// Background repeated images we cannot fix unfortunately
				if (imageSrc && imageSrc.match($.ifixpng.regexp.bg) && this.currentStyle.backgroundRepeat == 'no-repeat') {
					imageSrc = RegExp.$1;
					var x = this.currentStyle.backgroundPositionX || 0, y = this.currentStyle.backgroundPositionY || 0;
					if (x || y) {
						var css = {}, img;
						if (typeof x != 'undefined') {
							if (x == 'left') css.left = 0; 
							// if right is 0, we have to check if the parent has an odd width, because of an IE bug
							else if (x == 'right') css.right = $$.width() % 2 === 1 ? -1 : 0;
							else css.left = x;
						}
						if (typeof y != 'undefined') {
							// if bottom is 0, we have to check if the parent has an odd height, because of an IE bug
							if (y == 'bottom') css.bottom = $$.height() % 2 === 1 ? -1 : 0; 
							else if (y == 'top') css.top = 0;
							else css.top = y;
						}
						img = new Image();
						$(img).one('load', function() {
							var x,y, expr = {}, prop;
							// Now the image is loaded for sure, we can see if the background position needs fixing with an expression (in case of percentages)
							if (/center|%/.test(css.top)) {
								expr.top = "(this.parentNode.offsetHeight - this.offsetHeight) * " + (css.top == 'center' ? 0.5 : (parseInt(css.top) / 100));
								delete css.top;
							}
							if (/center|%/.test(css.left)) {
								expr.left = "(this.parentNode.offsetWidth - this.offsetWidth) * " + (css.left == 'center' ? 0.5 : (parseInt(css.left) / 100));
								delete css.left;
							}
							// Let's add the helper DIV which will simulate the background image
							$$.positionFix().css({backgroundImage: 'none'}).prepend(
								$('<div></div>').css(css).css({
									width: this.width,
									height: this.height,
									position: 'absolute',
									filter: hack.filter(imageSrc)
								})
							);
							if (expr.top || expr.left) {
								var elem = $$.children(':first')[0];
								for (prop in expr) elem.style.setExpression(prop, expr[prop], 'JavaScript');
							}
							$(this).remove();
						});
						img.src = imageSrc;
					} else {
						$$.css({backgroundImage: 'none', filter:hack.filter(imageSrc)});
					}
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			if ($$.css('position') != 'absolute') $$.css({position:'relative'});
		});
	};

})(jQuery);

$(function(){
	if ($.browser.msie) {
		if ($.browser.version == "6.0") $('.ifixpng').ifixpng();
	}
});


//不允许输入中文
var engOnly=function(str){
	for(i=0;i<str.length;i++){
		var c = str.substr(i,1);
		var ts = escape(c);
		if(ts.substring(0,2) == "%u"){
			return false;
		} else {
			return true;
		}
	}
}

//电子邮件验证
var emailOnly=function(str){
	var regEmail=/[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$/;
	if (regEmail.test(str)){
		return true;
	} else {
		return false;
	}
}

//手机号码验证
var mobileOnly=function(str){
	var regMobile=/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/;
	if (regMobile.test(str)){
		return true;
	} else {
		return false;
	}
}

//纯数字验证
var numOnly=function(str){
	var regNum=/^[0-9]{1,20}$/;
	if (regNum.test(str)){
		return true;
	} else {
		return false;
	}
}

//电话号码验证
var telOnly=function(str){
	var regTel=/^\({0,1}[0-9]{3}\){0,1}\-\({0,1}[0-9]{4}\){0,1}\-[0-9]{7,}$|^\({0,1}[0-9]{4}\){0,1}\-[0-9]{7,}$|^[0-9]{7,}$/;
	if (regTel.test(str))
		return true;
	else
		return false;
}

//日期的验证
var dateOnly=function(str){
	var date_array=str.split('-');
	if (date_array.length!=3) return false;
	var y=date_array[0];
	var m=date_array[1];
	var d=date_array[2];
	if (!numOnly(y)||!numOnly(m)||!numOnly(d)) return false;
	if (y.length!=4||m.length!=2||d.length!=2) return false;
	y=Number(y);
	m=Number(m);
	d=Number(d);
	if (y<1900||y>2050||m<1||m>12||d<1||d>31) return false;
	if ((m==4||m==6||m==9||m==11)&&d>30) return false;
	if ((y%100!=0&&y%4==0)||y%400==0){
		if (m==2&&d>29) return false;
	} else {
		if (m==2&&d>28) return false;
	}
	return true;
}
function addCookie(){
     if(document.all){
           window.external.addFavorite('http://www.softivo.com','鸿翮科技网站');
     }else if (window.sidebar){
           window.sidebar.addPanel('鸿翮科技网站', 'http://www.softivo.com', "");
     }
}
function setHomepage(){
    if (document.all){
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage('http://www.softivo.com');
    }else if (window.sidebar){
        if(window.netscape){
             try{ 
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
             }catch (e){ 
                alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" ); 
             }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage','http://www.softivo.com');
    }
}
$(function(){
	//设置首页和收藏   
	$(".web_control a").click(function(){
		if($(".web_control a").index(this)==1){
			addCookie();
		}else{
			setHomepage();
		}
	});	   
	//导航菜单
	$('#menuSitenav li').hover(function(){
		$('#menuSitenav div').hide();
		$(this).addClass('open').find('div').fadeIn('slow');
		$(this).css({'z-index': '1'}).siblings().css({'z-index': '0'});
	}, function(){
		$(this).removeClass('open').find('div').hide();
	});

	//输入框
	$('#ipt-keywords').focus(function(){
		if ($(this).val()=='请输入关键字...') $(this).val('');
	});
	$('#ipt-keywords').blur(function(){
		if ($(this).val()=='') $(this).val('请输入关键字...');
	});

	//表单验证
	$('form.form-validate').submit(function(){
		var itemRequired=$(this).find('input.required,select.required,textarea.required');
		for (var i=0;i<itemRequired.length;i++){
			if (itemRequired.eq(i).val()==''||itemRequired.eq(i).val()==null){
				alert(langs.form.error_uncomplete);
				itemRequired.eq(i).focus();
				return false;
			}
		}
		var colError=$(this).find('blockquote.error');
		if (colError.length>1||(colError.length==1&&!colError.parent().is('.row-submit'))){
			alert(langs.form.error_wrong);
			return false;
		}
		if ($(this).is('.form-ajax')){
			var arr=[];
			var i=0;
			$(this).find('input[name!=""]').each(function (){
				if (this.disabled || (this.checked==false && (this.type=="checkbox" || this.type=="radio"))){
				}else{
					arr[i++] = this.name+'='+$(this).val();
				}
			});
			$(this).find('select[name!=""]').each(function (){
				arr[i++] = this.name+'='+$(this).val();
			});
			$(this).find('textarea[name!=""]').each(function (){
				arr[i++] = this.name+'='+$(this).val();
			});
			var str = arr.join('&');
			var method=$(this).attr('method');
			var url=$(this).attr('action');
			var rowSubmit=$(this).find('div.row-submit');
			if (rowSubmit.find('blockquote').length<1){
				rowSubmit.append('<blockquote></blockquote>');
			}
			var theButton=$(this).find('button[type="submit"]');
			theButton.attr('disabled', true);
			var theForm=$(this);
			var containerMsg=rowSubmit.find('blockquote');
			containerMsg.removeClass().addClass('loading').text(langs.comment.submitting);
			$.ajax({
				type: method,
				url: url,
				data: str,
				dataType: 'json',
				error: function(){
					theButton.removeAttr('disabled');
					containerMsg.removeClass().addClass('error').text(langs.comment.failed);
					var imgCaptcha=theForm.find('img.img-captcha');
					imgCaptcha.attr('src', imgCaptcha.attr('rel')+Math.random());
				},
				success: function(callback){
					theButton.removeAttr('disabled');
					var imgCaptcha=theForm.find('img.img-captcha');
					imgCaptcha.attr('src', imgCaptcha.attr('rel')+Math.random());
					if (callback.status=='failed'){
						containerMsg.removeClass().addClass('error').text(callback.msg);
					}
					if (callback.status=='success'){
						containerMsg.removeClass().addClass('accepted').text(callback.msg);
						if (callback.dowhat=='direct'){
						window.setTimeout(function(){location.href=callback.url;},5000);	
						}
					}
				}
			});
			return false;
		}
	});

	//表单验证
	var iptBlur=function(which){
		if (which.is('.v-captcha')) return false;
		var value=which.val();
		var valueTrim=$.trim(value);
		var row=which.parent().parent();
		var tips=row.find('span.tips');
		var msgTips=tips.text();
		var msgError=tips.attr('rev');
		if(msgError==''||!msgError) msgError=tips.attr('title');
		if(msgError==''||!msgError) msgError=tips.text();
		if(msgError==''||!msgError) msgError='';
		var textReg=which.attr('rec');
		if(textReg==''||!textReg) textReg='';
		if(row.find('blockquote').length<1){
			row.append('<blockquote></blockquote>');
		}
		var boxMsg=row.find('blockquote');
		if(which.is('.required')&&(valueTrim==''||valueTrim==null)){
			boxMsg.removeClass().addClass('error').text(langs.form.tip_required);
		} else if(tips.length<1){
			if(valueTrim!=''&&valueTrim!=null){
				boxMsg.removeClass().removeClass().addClass('accepted').text('');
			} else {
				boxMsg.remove();
			}
		} else if(which.is('.v-length')&&textReg!=''&&(valueTrim.length<Number(textReg.split(',')[0])||valueTrim.length>Number(textReg.split(',')[1]))){
			boxMsg.removeClass().addClass('error').text(msgError);
		} else if(which.is('.v-clone')&&which.val()!=$('#'+which.attr('rel')).val()){
			boxMsg.removeClass().addClass('error').text(msgError);
			which.val('');
		} else if(which.is('.v-email')&&value!=''&&value!=null&&!emailOnly(value)){
			boxMsg.removeClass().addClass('error').text(langs.form.tip_wrongemail);
		} else if(which.is('.v-number')&&value!=''&&value!=null&&!numOnly(value)){
			boxMsg.removeClass().addClass('error').text(msgError);
		} else if(which.is('.v-tel')&&value!=''&&value!=null&&!telOnly(value)){
			boxMsg.removeClass().addClass('error').text(msgError);
		} else if(which.is('.v-mobile')&&value!=''&&value!=null&&!mobileOnly(value)){
			boxMsg.removeClass().addClass('error').text(msgError);
		} else if(which.is('.v-date')&&value!=''&&value!=null&&!dateOnly(value)){
			boxMsg.removeClass().addClass('error').text(msgError);
		} else if(value!=''&&value!=null){
			boxMsg.removeClass().removeClass().addClass('accepted').text(msgTips);
		} else {
			boxMsg.remove();
			tips.show();
		}
	}
	$('form.form-validate input.text,form.form-validate textarea').focus(function(){
		var row=$(this).parent().parent();
		var tips=row.find('span.tips');
		if (tips.length<1) return false;
		var msgHelp=tips.attr('title');
		if(msgHelp==''||msgHelp==null) msgHelp=tips.text();
		tips.hide();
		if (row.find('blockquote').length<1){
			row.append('<blockquote></blockquote>');
		}
		row.find('blockquote').removeClass().text(msgHelp);
	});
	$('form.form-validate input.text,form.form-validate textarea').blur(function(){
		var thisInput=$(this);
		setTimeout(function(){iptBlur(thisInput);}, 500);
	});
	$('form.form-validate button[type="reset"],form.form-validate input[type="reset"]').click(function(){
		var theForm=$(this).parents('form');
		theForm.find('blockquote').remove();
		theForm.find('span.tips').show();
	});
	
	//金额计算
	$('#ipt-num-count').keyup(function(){
		var value=$(this).val();
		$(this).val(value.replace(/^[^1-9]{1}|[^0-9]*/g,''));
		if (value!=''){
			var totalCost=Number(value)*Number($('#txt-price').text());
			if (String(totalCost).split('.').length<2){
				totalCost+='.00';
			} else if (String(totalCost).split('.')[1].length<2){
				totalCost+='0';
			}
			$('#txt-cost').text(totalCost);
		}
	});


	//图片幻灯片
	var resizeProGallery=function(){
		var thePic=$('#showpic-picholder img');
		var thePicWidth=thePic.width();
		var thePicHeight=thePic.height();
		var picMaxwidth=Number((thePic.attr('rel').split(','))[0]);
		var picMaxheight=Number((thePic.attr('rel').split(','))[1]);
		if (thePicWidth<=picMaxwidth && thePicHeight<=picMaxheight){
			
		}
		if (thePicWidth>picMaxwidth && thePicHeight<=picMaxheight){
			thePic.width(picMaxwidth);
		}
		if (thePicWidth<=picMaxwidth && thePicHeight>picMaxheight){
			thePic.height(picMaxheight);
		}
		if (thePicWidth>picMaxwidth && thePicHeight>picMaxheight){
			if ((thePicWidth/thePicHeight)>(picMaxwidth/picMaxheight)){
				thePic.width(picMaxwidth);
			} else {
				thePic.height(picMaxheight);
			}
		}
	}
	if (document.getElementById('showpic-picholder')) resizeProGallery();
	$('#showpic-gallery ul a').click(function(){
		if ($(this).parent().is('.selected')) return false;
		var item=$(this).parent();
		var itemWidth=parseInt(item.css('width'));
		var itemMarginRight=parseInt(item.css('margin-right'));
		var itemBorderRight=parseInt(item.css('border-right-width'));
		var itemPaddingRight=parseInt(item.css('padding-right'));
		var itemMarginLeft=parseInt(item.css('margin-left'));
		var itemBorderLeft=parseInt(item.css('border-left-width'));
		var itemPaddingLeft=parseInt(item.css('padding-left'));
		var itemSpace=(itemWidth+itemMarginRight+itemBorderRight+itemPaddingRight+itemMarginLeft+itemBorderLeft+itemPaddingLeft);
		var total=$('#showpic-gallery ul a').length;
		var thisone=(item.prevAll('li').length)+1;
		var leftValue=0;
		if (thisone<(total-2)&&thisone>2){
			leftValue=(-itemSpace)*(thisone-2);
		}
		if (thisone>(total-3)){
			leftValue=(-itemSpace)*(total-4);
		}
		item.addClass('selected').siblings().removeClass('selected');
		var picsource=$(this).attr('href');
		$('#showpic-picholder').attr('href', picsource).find('img').attr('src', picsource);
		resizeProGallery();
		$(this).parents('ul').animate({left:leftValue+'px'},{queue:false,duration:300});
		return false;
	});
	$('#showpic-gallery a.button').click(function(){
		var num=$(this).parent().find('ul li.selected').prevAll('li').length;
		if (num==0&&$(this).is('.prev')) $(this).parent().find('ul a').eq(-1).click();
		if (num==($(this).parent().find('ul li').length-1)&&$(this).is('.next')) $(this).parent().find('ul a').eq(0).click();
		if ($(this).is('.prev')) num--;
		if ($(this).is('.next')) num++;
		$(this).parent().find('ul a').eq(num).click();
		return false;
	});


	//评论与留言

	//刷新验证码
	$('#form-comment img.img-captcha').click(function(){
		$(this).attr('src', 'CheckYanZheng.ashx?'+Math.random());
	});
});
