$.ajaxSetup({
	crossDomain: false,
	timeout: 10000
});

window.onerror = function(){
	if(arguments[0].match(/已释放|a freed script/)) return true;
}

var Dwd = (function(){
	var loginSuccessCallbackList = [];

	return {
		startTime: new Date().getTime(),
		startPath: decodeURI(document.location.href.replace(/\/[^\/]+$/,'/').replace('file:///', '')),
		version: '',
		host: '',
		init: function(){
			var self = this;
			var container = $('.container');

			self.version = (function(){
				try{
					return Fso.read('version.pur5').match(/version=([^#]+)#/)[1];
				}catch(e){
					return '';
				}	
			}())

			Module.loads([
				'serverList',
				'dialog',
				'sound'
			], $(document.body));
			
			Ui.layoutTo($('#serverList'));
			Ui.setDragArea(0, 0, 290, 30);
			setTimeout(function(){
				Module.loads([
					'login',
					'progress'
				], $(document.body));
				
				Module.load('menu', $('#main .menu'));
				Module.load('status', $('#main .status'))
				
				$('#window_btn')
				.find('.return_btn,.max_btn').click(function(){
					Ui.max();
				}).end()
				.find('.mini_btn').click(function(){
					Ui.mini();
				}).end()
				.find('.mini_totray').click(function(){
					Ui.miniToTray();
				}).end()
				.find('.close_btn').click(function(){
					Dwd.close();
				});
				
				$('.form-icon').dblclick(Dwd.close);
				
				$('#max_dbl_area').dblclick(function(){
					$('#window_btn').find('.max_btn').click();
					return false;
				}).bind('selectstart', function(){//标题栏双击缩放不选中
					return false;
				});
				
				$('.splash_close_btn').click(function(){
					window.close();
				});				

				$('.version').html(Dwd.version);
				
				$('#main').bind("resize", function(){
					$('.main').height($(window).height() - 139);
				});

				//小工具
				(function(){
					var $win=$('#window_btn');
					var $list=$win.find('.tools_list');
					var t1,t2,delay=200;
					$list.on('click','a',function(){
						$list.hide();
						return false;
					}).on('click','.repair',function(){
						window.showModelessDialog('../package/tools.html','','dialogHeight:260px;dialogWidth:630px;status:no;');
					}).on('click','.exit',function(){
						Dwd.close();
					}).on('click','.totray',function(){
						Ui.miniToTray();
					});

					$win.on({
						mouseenter:function(){
							clearTimeout(t2);
							$list.show();
						},
						mouseleave:function(){
							t1=setTimeout(function(){
								$list.hide();
							},delay)
						}
					},'.tools_btn');

					$list.on({
						mouseenter:function(){
							clearTimeout(t1);
						},
						mouseleave:function(){
							t2=setTimeout(function(){
								$list.hide();
							},delay);
						}
					});

				})();
				
				$('.shopChange-btn').click(function(){
					Shop.change(function(){
						try{
							var refreshShopInfo = $('#frame iframe').get(0).contentWindow.refreshShopInfo;
							if(refreshShopInfo){
								refreshShopInfo();
							}else{
								$('#frame iframe').get(0).contentWindow.location.reload();
							}
						}catch(e){}
					});
				});				
			}, 10);
		},
		connectionTest: function(cb){
			$.ajax({
				url: this.makeFullPath('test-connection.html'),
				type: 'get',
				dataType: 'text',
				cache: false,
				success: function(data){
					if(data == 'ok'){
						cb && cb(true);
					}else{
						alert('网络异常，请切换其它服务器登录！\n' + data);
					}
				},
				error: function(){
					alert('网络异常，请切换其它服务器登录！');
				}
			});
		},
		maxStatusChange: function(isMax){
			if(isMax){
				$('.return_btn').parent().show();
				$('.max_btn').parent().hide();
			}else{
				$('.return_btn').parent().hide();
				$('.max_btn').parent().show();
			}
		},
		setShopId: function(shopId){
			this.shopId = shopId;
		},
		makeFullPath: function(path){
			return str_replace('http://{1}/{2}', this.host, path);
		},
		interface: function(name, url, data, cb){
			$.ajax({
				url: this.makeFullPath('interface/' + url),
				type: 'post',
				dataType: 'json',
				data: $.extend({}, data, {
					token: User.getToken()
				}),
				success: function(result, textStatus, jqXhr){
					if(result){
						result.message?cb(false, name + '出错：' + result.message, result):cb(result);
					}else{
						cb(false, ajaxError(name, jqXhr, textStatus));
					}
				},
				error: function(jqXhr, textStatus){
					cb(false, ajaxError(name, jqXhr, textStatus), false);
				}
			});
		},		
		close: function(){
			Dialog.alert({
				title: '退出系统',
				content: '您确定要退出本程序吗？',
				style: {
					width: 250,
					height: 35
				},
				button: {
					'确 定': false,
					'是(Y)': function(){

						User.loginOut(false, function(){
							window.close();
						});
					},
					'否(N)': function(){}
				}
			});
		},
		alert: function(layout, noAnimate){
			var noAnimate = true;
			var $doc = $(document);
			$('#fitDialog_shadow').css({
				opacity: 0.1
			}).show().focus();
			$('#fitDialog-shadow-cover').css({
				opacity: 0.4
			}).show();
			if(noAnimate){
				layout.css({
					'margin-top': Math.max(-$(window).height()/2,-layout.height()/2)-1,
					'margin-left': 0-layout.outerWidth()/2,
					display: 'block'
				});
			}else{
				layout.css({
					'margin-top': 0,
					'margin-left': 0-layout.outerWidth()/2,
					display: ''
				}).animate({
					'margin-top': 0-layout.height()/2-1
				}, 'fast');
			}
		},
		loginSuccess: function(cb){
			if(typeof(cb) == 'function'){
				if(typeof(User) == 'object' && User.isLogined()){
					cb();
					return;
				}

				loginSuccessCallbackList.push(cb);
				return;
			}

			$.ajax({
				url: User.makeFullPath('DefaultPage/client/loginsuccess.html'),
				dataType: 'json',
				cache: false,
				success: function(Result){
					$.include(User.makeFullPath('DefaultPage/client/'), Result.url);
				},
				error: function(jqXhr, textStatus){
					alert('登录失败，请重开软件！\n' + [textStatus, jqXhr.responseText]);
				}
			});
		},
		loginSuccessCallback: function(){
			$.each(loginSuccessCallbackList, function(index, cb){
				cb();
			});
		},
		startTbDesigner: function(){
			var designerPath = '../log/designer.pur5',
				designerPathContent = Fso.read(designerPath),

				path = getFields({
					path: /installDir=(.+)/
				}, designerPathContent).path,

				$posBtn,
				$openBtn;

			if(path){
				path = path.replace(/^\s+|\s+$/g, '');
			}

			Dialog.alert({
				title: '一键装修',
				content: '<div><input type="file" style="display:none;" /><span class="selectTip">请选择装修软件……</span><span class="path hide">软件位置：<span class="designerPath" style="color:#399be0;"></span><a href="#" class="posBtn" style="margin-left:3px; text-decoration:underline;">重新定位</a></span></div>',
				action: function($content, $layout){
					$posBtn = $layout.find('.buttons').find('span:contains("定位软件")');
					$opentBtn = $layout.find('.buttons').find('span:contains("打开软件")');

					function checkBtn(){
						if(path && Fso.fileExists(path)){
							$content.find('.path')
							.find('.designerPath').text(path).end().show()
							.siblings().hide();						
							$opentBtn.show();
							$posBtn.hide();
						}else{
							$posBtn.show();
							$opentBtn.hide();
						}
					}

					$content.find('.posBtn').click(function(){
						$content.find('input[type=file]').click();
					});

					$content.find('input[type=file]')
					.bind('change', function(){
						var selectedFilePath = $content.find('input[type=file]').val(),
							reg = /^.+.exe$/;

						if(!reg.test(selectedFilePath)){
							alert('安装软件选择错误，请重新选择！');
							return;
						}

						path = selectedFilePath;
						$content.find('.designerPath').text(path);
						Fso.write(designerPath, 'installDir=' + path);

						checkBtn();									
					});

					checkBtn();					
				},
				style: {
					width: 280
				},
				button: {
					'确 定': false,
					'定位软件': function($content){
						$content.find('input[type=file]').click();
						return false;
					},
					'打开软件': function($content){
						Fso.exec(path);
					},
					'下载软件': function(){
						var downloadPageUrl = 'http://www.diwudai.com/download/';
						$.ajax({
							url: downloadPageUrl,
							cache: false,
							success: function(html){
								var url = getFields({
									url: /<a class="download-a" href="([^"]+)" target="_blank">下载<\/a>\s+.+?装修软件/
								}, html).url;

								if(!url){
									this.error();
								}else{
									top.Ui.openIE(url);
								}
							},
							error: function(){
								top.Ui.openIE(downloadPageUrl);
							}
						});
					}
				}
			});
		}	
	}
})();

function Class(MyClass){
	var className = MyClass.toString().match(/function\s+(\S+)?\(/)[1];

	window.Class[className] = MyClass;
	window[className] = new MyClass();

	className = null;
}

$(function(){
	$(window).bind('beforeunload', function(){
		User.loginOut(false);
	});

	$.include('scripts/', [
		'inc/function.js',
		'inc/jquery.stringify.js',
		'inc/jquery.pur5.md5.js',
		'inc/jquery.xml2json.js',

		'inc/dwd.ui.js',
		'inc/dwd.user.js',
		'inc/dwd.shop.js',
		'inc/dwd.snap.js',

		'inc/module.js',
		'inc/serverModule.js',
		'inc/express.js',
		'inc/realyIEVersion.js',

		'inc/fso.js',
		'inc/fileTransfer.js',
		'inc/imageTools.js',
		'inc/fileBrowser.js',
		'inc/miniBrowser.js',
		
		'inc/message.js'/*,
		'inc/taobao.user.js',
		'inc/taobao.api.js'*/
	], function(){
		Dwd.init();
	});
});