//init $gz package

var StringExtend = {
	format: function() {
		var text = this;
		if (arguments.length <= 0) {
			return text;
		}
	
		var tokenCount = arguments.length - 1;
		for (var token = 0; token <= tokenCount; token++) {
			text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token]);
		}
		return text;
	}
};

$.extend(true, String.prototype, StringExtend);

$gz.www.PROGRESS = {
		properties: {
			ajaxStatus: 0,
			loaderImageUrl: $gz.www.property.CONST.IMAGE_DOMAIN + "/images/v3/com/loading.gif"
		},
		
		progressBox: null,
		notificationHandlers: new ArrayList(),
		loadingTable: new Hashtable(),
		
		appendLoadingImage: function(container) {
			if (container && container.get(0) && !this.loadingTable.contains(container.attr("uid"))) {
				var uid = UIDUtil.createUID();
				var loadingImage = $('<img class="loading_img" src="' +this.properties.loaderImageUrl+ '" width="42" height="42"/>');
				this.loadingTable.add(uid, {current: loadingImage, orgine: container.children()});
				container.html("").attr("uid", uid).append(loadingImage);
			}
		},
		
		getProgressBox: function(title, duration) {
			if (!this.progressBox) {
				this.progressBox = new ProgressBox(null, {title: title || '<img class="loading_img" src="' +this.properties.loaderImageUrl+ '" width="28" height="28"/>',
					content: '<strong class="loading">요청한 작업을 처리하고 있습니다.<br /><span>잠시만 기다려 주세요.</span></strong>', modal: true, mode: 2});
			}
			return this.progressBox;
		},
		
		notify: function(type) {
			for (var i=0; i<this.notificationHandlers.length(); i++) {
				this.notificationHandlers.get(i)(type);
			}
		},
		
		registerNotificationHandler: function(handler) {
			return this.notificationHandlers.add(handler);
		},
		
		removeProgressBox: function() {
			if (this.progressBox) {
				this.progressBox.dispose();
				this.progressBox = null;
			}
		},
		
		removeLoadingImage: function(container) {
			var uid = container.attr("uid");
			if (this.loadingTable.contains(uid)) {
				this.loadingTable.get(uid).current.detach();
				container.append(this.loadingTable.get(uid).orgine);
				this.loadingTable.remove(uid);
			}
		}
};


$gz.www.util = {

	enableNoimage : true	
	,createPanel : function(obj){
	
			var url = $(obj).attr("href") || $(obj).attr("url");
			var title = $(obj).attr("title");

			var panel = new Panel(url, {title:title , draggable: true});
			var panel_close = function(event){
				
			};
			panel.addEvent("close", $.proxy(panel_close, this), this);
			
			return false;
		}	
		
	,click : function(selector){
		if(document.createEvent){
			var e = document.createEvent('MouseEvents');
		    e.initEvent( 'click', true, true );

		    selector.each(function(){
		    	this.dispatchEvent(e);
		    });
		}else{
			selector.get(0).click();
		}
	}
		
	,bindNoImageEvent : function(){
		if($gz.www.util.enableNoimage){
			$("img[errorbind!='true']").error(function(evt){
				$gz.www.util.changeNoImage(this);
				$(this).attr("errorbind","true");
			});
		}
	}

	,changeNoImage : function(obj){

		if($(obj).attr("noimage")!="true"){

			$(obj).unbind("error");
			$(obj).attr("noimage","true");
			
			var width = $(obj).attr("width");
			var height = $(obj).attr("height");

			var attr_width = obj.getAttribute('width');
			var attr_height = obj.getAttribute('height')

			if(width!=attr_width || height!= attr_height){
				width = attr_width;
				height = attr_height;
			}
				
			if(width>0 && height>0 ){
				var noimage_name = "" + width + "x" + height + ".jpg";
				$(obj).attr("origin_src",$(obj).attr("src"));
				$(obj).attr("src", $gz.www.property.CONST.IMAGE_DOMAIN + "/images/v3/error/" + noimage_name);
			}
		}
	}
};


$(document).ready(function(){
	
	//image error chage image
	
	if($.browser.msie && $gz.www.util.enableNoimage){
		$(window).bind('load', function() {
			$("img[errorbind!='true']").each(function() {
			    if((typeof this.naturalWidth != "undefined" &&
			        this.naturalWidth == 0 ) 
			        || this.readyState == 'uninitialized' ) {
			    	$gz.www.util.changeNoImage(this);
			    }
			    $(this).attr("errorbind","true");
			});
		});
	}else{
		$gz.www.util.bindNoImageEvent();
	}
	
	// ajax event handler
	$("<div>").bind({
		ajaxStart: function(e, options){
			$gz.www.PROGRESS.properties.ajaxStatus = 0;
			if (undefined == options.useProgress || options.useProgress) {
				if (undefined != options.progressContainer) {
					$gz.www.PROGRESS.appendLoadingImage(options.progressContainer);
				} else {
					setTimeout(function(){
						if ($gz.www.PROGRESS.properties.ajaxStatus == 0)
							$gz.www.PROGRESS.getProgressBox().setProgress(0, 1);
					}, 500);
				}
			}
		},
		ajaxComplete: function(e, xhr, options, ex){
			$gz.www.PROGRESS.properties.ajaxStatus = 1;
			$gz.www.PROGRESS.notify(options.url);

			if (undefined == options.useProgress || options.useProgress) {
				if (undefined != options.progressContainer) {
					$gz.www.PROGRESS.removeLoadingImage(options.progressContainer);
				} else {
					$gz.www.PROGRESS.removeProgressBox();
				}
			}
			
			$gz.www.util.bindNoImageEvent();
		},
		ajaxError: function(e, xhr, options, ex){
			$gz.www.PROGRESS.properties.ajaxStatus = 2;
			if (undefined == options.useProgress || options.useProgress) {
				if (undefined != options.progressContainer) {
					$gz.www.PROGRESS.removeLoadingImage(options.progressContainer);
				} else {
					$gz.www.PROGRESS.removeProgressBox();
				}
			}
			
			if(options.complete)
				options.complete = function(){
					return false;
				};
			
			if(xhr && xhr.status){
				switch(xhr.status){
					case 401:
						//var retUrl = encodeURIComponent(xhr.getResponseHeader("Referer"));
						//alert("ajax login fail retUrl:" + retUrl + ",로긴 redirec 차후 설정");
						//document.location.href = String("{0}?retUrl={1}").format($gz.www.PROGRESS.properties["auth.login.url"], retUrl);
						return false;
					break;
				}
			}
		}
	});
	
	
	
	// global navigator
	var cls_gnbcontroller = function(){
		this.current = "";
		this.mapping = {
			"myrecord" : $(".btn_myrecord,.gnb_sub_myrecord")
			,"nasmozon" : $(".btn_nasmozon,.gnb_sub_nasmozon")
			,"tournament" : $(".btn_tournament,.gnb_sub_tournament")
			,"community" : $(".btn_community,.gnb_sub_community")
			,"lesson" : $(".btn_lesson,.gnb_sub_lesson")
			,"newsncol" : $(".btn_newsncol,.gnb_sub_newsncol")
		};
	};
  
	var method_gnbcontroller = {
		focus : function(key){
			if(key==this.current) return;
			this.reset(this.current);

			if(this.mapping[key]){
				this.mapping[key].addClass(key+'_on');
				this.current = key;
			}else{
				this.current = "";
			}
		}
		, reset : function(key){
			if(this.mapping[key]) {
				this.mapping[key].removeClass(key+'_on');
				this.current = "";
			}
		}
	};

	$.extend(cls_gnbcontroller.prototype , method_gnbcontroller);

	var _gnbcontroller = new cls_gnbcontroller();

	$('.gnb_group,.gnb_sub').bind({
		mouseover:function(){
			$('.gnb_sub').show();
		}
		,mouseout :function(){
			$('.gnb_sub').hide();
			if ( _gnbcontroller.current != "" ) {
				_gnbcontroller.reset(_gnbcontroller.current);
			}
		}
	});

	$('.gnb_group a').mouseover(function(obj){
		var targetsplit = obj.currentTarget.className.split("_");
		_gnbcontroller.focus(targetsplit[targetsplit.length-1].split(' ')[0]);
	});

	$('.gnb_sub ul,.gnb_sub dl').mouseover(function(obj){
		var targetsplit = obj.currentTarget.className.split("_");
		_gnbcontroller.focus(targetsplit[targetsplit.length-1].split(' ')[0]);
	});
	
	$(this).find(".fsite_area").each(function(e){
		$(this).find(".family").data("show",false).click(function(){
			if ($(this).data("show") == false){
				$(".family_site_area").show();
				$(this).data("show",true).addClass("on");
			}else{
				$(".family_site_area").hide();
				$(this).data("show",false).removeClass("on");
			}
			return false;
		});
	});
	
	$("body").click(function(){
		if ($(".family").data("show") == true){
			$(".family_site_area").hide();
			$(".family").data("show",false).removeClass("on");
		}
	});


	$('.btn_startpage,.strat_page').click(function(){	
		if ($.browser.msie == true ) {
			this.style.behavior='url(#default#homepage)';
			this.setHomePage('http://www.golfzon.com/');
		} else {
			alert("현재 브라우저에서는 지원하지 않는 기능입니다.");
		}
		return false;
	});
	
	
});


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 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
 *
 */
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;
};

