/** pack for apps.js **/

function login_popup(form_selector, content_selector, ref, onclose) {

	var $buzz_login_form = $(form_selector);
	var action = $buzz_login_form.attr('action');

	var regex=/[?&]ref=[^?&]+/gi;

	var action_url = $buzz_login_form.attr('action');

	// 沒有 ref 就串上ref
	if(action_url.match(regex) == null && ref){
		$buzz_login_form.attr('action', action.replace(regex, "")+'?ref='+encodeURIComponent(ref));
	}
	
	if(!onclose) {
		onclose = function() {}
	}
	
	$.fn.logincolorbox({inline:true, href:content_selector, opacity:0.7, width:'500', onClosed:onclose});

}	

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '',        strict = !! argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {                return true;
            }
        }
    } else {
        for (key in haystack) {            if (haystack[key] == needle) {
                return true;
            }
        }
    } 
    return false;
}

function escapeHtml(unsafe) {
	 
  if(unsafe == null) {
	  return '';
  }
	
  return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

function fb_multi_friend_selector(action, type, actiontext, width, height, display) {

	if(action == null) {
		alert('plz input action');
		return false;
	}

	if(width == null) {
		width = 750;
	}

	if(height == null) {
		height = 600;
	}

	if(display == null) {
		display = 'iframe';
	}

	 //Get the original default size
	 var originalSize = FB.UIServer.Methods["fbml.dialog"].size;

	 //Assign a new size you want
	 FB.UIServer.Methods["fbml.dialog"].size = {width:width, height:height};

	 var str = "<fb:fbml><fb:request-form action='"+action+"' method='POST' invite='true' type='"+type+"' content='夢幻情人節，集氣奪好禮~<fb:req-choice url=\"http://w3.goodday365.cc/test/friend\" label=\" 幫他集氣 \" />'>";
	 str += "<fb:multi-friend-selector showborder='false' actiontext='"+actiontext+"'>";
	 str += "</fb:request-form></fb:fbml>";
	 var content = {
	  method: "fbml.dialog",
	  fbml: str,
	  width: width,
	  height: height
	 };
	 //Set the dialog to be popup
	 content.display = display;

	 FB.ui(content);

	 //Restore the default size immediately
	 FB.UIServer.Methods["fbml.dialog"].size = originalSize;
}


function copy_to_scrapbook(selector){
	var js = '';
	var $obj = $(selector);
	var javascript_object = $obj[0];
	javascript_object.select();
	//js=javascript_object.createTextRange();
	//js.execCommand("Copy");
}

function preview_button(selector, action) {

  	var t = new Date().getTime();
    var form = $(selector);
    var old_action = form.attr('action');

    form.attr('target', '_blank');
	form.attr('action', action+'?v=' + t);
    form.submit();
	unprocessing();
    form.attr('target', '');
    form.attr('action', old_action);

}

function add_load_image(content_selector, offset_top, offset_left) {

		$content = $(content_selector);

		if(offset_top == null) {
			offset_top = 0;
		}

		if(offset_left == null) {
			offset_left = 0;
		}

		$content.css({
			'position':'relative'
		});

		var width = $content.width();
		var height = $content.height();

		var $img = $('<img>');
		$img.attr('src', '/public/images/indicator.gif');
		$img.css({
				'position':'absolute'
			,	'top': parseInt(height / 2) + parseInt(offset_top)
			, 	'left': parseInt(width / 2) + parseInt(offset_left)
		});

		$img.appendTo($content);

		return $img;

}

function loading_and_change_photo_size(size, small_image_selector, big_image_selector
		, content_selector) {

		if(size == null) {
			size = '';
		}

		if(small_image_selector == null) {
			small_image_selector = '.small_images';
		}

		if(big_image_selector == null) {
			big_image_selector = '#product_image';
		}

		if(content_selector == null) {
			content_selector = '#product_image_content';
		}

		var replace_src = '';

		$(small_image_selector).click(
			function() {

				var $this = $(this);
				var src = $('img', $this).attr('src');
				var original_size = src.split('/').slice(-2)[0];

				$load_img = add_load_image(content_selector);

				replace_src = src.replace(original_size, size);

				var preload_img = new Image;

				preload_img.onerror = function (evt) {
				    alert("can't be loaded.");
				    $load_img.remove();
				}

				preload_img.onload = function(){
					$load_img.remove();
				};

				preload_img.src = replace_src;

				$(big_image_selector).attr('src', replace_src);

				return false;
			}
		);

}


function text_count(textarea, selector)
{
	$(selector).html(' '+$(textarea).val().length+ ' ');
}

function jq_swap_image(selector, src, image_selector){

		var osrc = '';
		var $image = '';

		if(image_selector == null) {
			image_selector = '.target_image';
		}

		$(selector).hover(
			function(){
				$image = $(this).find(image_selector);
				osrc = $image.attr('src');
				$image.attr("src", src);
			},
			function(){
				$image.attr('src', osrc);
			}
		);

}


function fb_share(u, callback, t, display) {

		if(display == null) {
			display = 'popup';
		}

   		var share = {
		   method: 'stream.share',
		   u: u,
		   display: display,
		   t: t

		};

		FB.ui(share, callback);
}

function word_count_down(textarea_selector, count_word_selector, limit_length) {
		$(textarea_selector).keyup(
			function() {
				var value = $(this).val();
				var word_length = value.length;
				if(word_length > 250){
					$(this).val(value.substring(0, limit_length));
					return false;
				}
				$(count_word_selector).html(limit_length-parseInt(word_length));
			}
		);
}

function _no_error_symbol(errorMap,errorList,container) {

	if(errorList.length <= 0) {
		return false;
	}

	try{
  		$.scrollTo(0, 800);
  	}catch(err){
  		alert('please include jq_include_scrollto');
  	}


	$('div.registerErrIcon').remove();

	var message = '';

	for(var i=0;i<errorList.length;i++)
	{

		message += errorList[i].message;
		if(i != (errorList.length-1))
		{
			message += ' / ';
		}

	}

	$('.error').css({display:'block'});

	container.html(message);

}

function delete_confirm(selector, message, url)
{
	$(selector).click(
		function(event) {

			if (document.all) event.returnValue = false;// for IE
  		 			else event.preventDefault();

			if(!confirm(message)) {
					return false;
			}

			if(url != null) {
				location.href = url;
				return false;
			}

			location.href = $(this).attr("href");

			return false;
		}
	);
}

// @deprecated. 使用 javascript/admin_rules.js 取代
function tr_change_color(color) {

	if(color == null) {
		color = '#fffada';
	}

	$("tr").hover(
			function(){
				$(this).attr('bg', $(this).css("background-color"));
				$(this).css("background-color", color);
			},
			function(){
				$(this).css("background-color", $(this).attr('bg'));
			}
	);
}

function confirm_delete(obj, event, title, href)
{

	 if (document.all) window.event.returnValue = false;// for IE
  		 else event.preventDefault();

	var title = title || '確定要刪除嗎?';
	if(!confirm(title))
	{
		return false;
	}

	if(href == null)
	{
		location.href = obj.href;
	} else {
		location.href = href;
	}

}
// 更換圖片size
function change_photo_size(obj, size, photo_id) {
	var a_obj = $(obj);
	// 原來的src
	var src = $('img', a_obj).attr('src');
	// 取得原來的尺寸
	var original_size = src.split('/').slice(-2)[0];
	$('#'+photo_id).attr({src:src.replace(original_size, size)});
}

// 按下enter可以submit
// 搜尋時按enter
function check_submit(e, form_expr)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	// 按下enter
	if(keycode == 13)
	{
		$(form_expr).submit();
	}
}

function add_inner_logic(a) {

  if(a == '')
  {
  	return 0;
  }
  else
  {
  	return 1;
  }

}

/**
 ex:rules price_begin: {
				digits:true,
				inner:"#price_begin,#price_end"
 }

 $(document).ready裡放
 add_inner('inner','請輸入品牌價格');

 all_require:true 一定要輸入

**/
function add_inner(name, message, all_require){

	jQuery.validator.addMethod(name, function(value, element, params) {

		var bool = new Array();
		var patt = '';
		var is_match = '';


		$(params).each(
			function(i,obj){
				if($(obj).attr('disabled') == true) {
					bool[i] = 1;
				} else {
					bool[i] = add_inner_logic(obj.value);
				}
			}
		)
		if(all_require == null)
		{
			patt = /([0]+[1]+|[1]+[0]+)/;
		}
		else
		{
			patt = /([0]+)/;
		}

		// 如果match的話，要回傳true，才能產生錯誤
		// 全選，因為找不到0就是不match
		is_match = patt.test(bool.join(""));

		return !is_match;


	}, message);
}



// for set_error_message
function _insert_error_div() {

		if($('.error_span').length > 0) { return false; }
		
		if($('#FlashNotice').length > 0) { return false;}

		var content_string = '<div id="FlashNotice" style="padding-bottom:10px;">';
		content_string += '<div class="error" style="display: none;">';
		content_string += '<div>';

		content_string += '<span class="error_span"></span>';
		content_string += '</div>';
		content_string += '</div>';
		content_string += '</div>';

		$('.conect, .conect_ajax, #campaign_error_content').prepend(content_string);
}

function _remove_error_div() {

		$('#FlashNotice').remove();
}

// for set_error_message
function _default_show_errors(errorMap,errorList,container) {
	$('.error').css({display:'block'});

	try{
  		$.scrollTo(0, 800);
  	} catch(e) {
  		alert('please include jq_include_scrollto');
  	}


	$('div.registerErrIcon').remove();

	var message = '';

	for(var i=0;i<errorList.length;i++)
	{

		var em = $('<div class="registerErrIcon"></div>');

		var next_td = $(errorList[i].element).parents("td").next("td");

		if(next_td[0] == null)
		{
			$(errorList[i].element).parents('tr').append('<td></td>');
			next_td = $(errorList[i].element).parents("td").next("td");
		}

		var registerIcon = next_td.children(".registerErrIcon");
		if(registerIcon[0] == null)
		{
			em.appendTo(next_td);
		}

		message += errorList[i].message;
		if(i != (errorList.length-1))
		{
			message += ' / ';
		}

	}
	container.html(message);
}

function default_submit_handler(form)
{
	$('.error').hide();
	processing();

	if(form.submit.length > 1) {
		form.submit[0].submit();
	} else {
		form.submit();
	}
}

// ex: set_error_message(form_name, rules, messages, _no_error_symbol);
function set_error_message(form_name, rules, messages, error_callback, submit_callback)
{

	var showErros = '';

	var exist_callback = (error_callback != null);

	if(exist_callback) {
		showErrors = error_callback;
	} else {
		showErrors = _default_show_errors;
	}
	
	var submit_handler = '';

	if(submit_callback != null) {
		submit_handler = submit_callback;
	} else {
		submit_handler = default_submit_handler;
	}

	var validator = $(form_name).bind("invalid-form.validate", function() {

	}).validate({
				onclick: false,
				focusInvalid: false,
				focusCleanup: false,
				onkeyup: false,
				onfocusout: false,
				showErrors: function(errorMap, errorList) {
					removeActionMessage();
					_insert_error_div();
					var container = $('.error');
					showErrors(errorMap, errorList, container);
				},
				beforeSubmit: function() {},
				rules: rules,
				messages: messages,
				submitHandler: function(form) {
					submit_handler(form);
				}
	});
}

function showActionMessage(message, message_type, append_message) {

	if(append_message == null) {
		removeActionMessage();
	}

	if(typeof message_type == "undefined") message_type = "success";

	if (message.indexOf("<p>") > 1) {
		var m = "<div class='message " + message_type + "'>" + message + "</div>";
	} else {
		var m = "<div class='message " + message_type + "'><p>" + message + "</p></div>";
	}

	if(document.getElementById("FlashNotice")) {	// already has message
		$("#FlashNoticeContent table tr td").append(m);
	} else {
		var t = "<div id='FlashNotice' align='center'><div class='clear'/><div id='FlashNoticeContent'><table><tr><td>"
				+ m
				+ "</td></tr></table></div></div>";

	   $("#FlashNoticeContainer").html(t);
	}
}

function removeActionMessage() {
	$("#FlashNoticeContainer").html("");
}

function close_tb(val) {

	if(window.parent && typeof window.parent.tb_remove == "function") {6
		if(typeof val != "undefined") {
			parent.tb_remove(val);
		} else {
			parent.tb_remove(null);
		}
	} else {
		window.close();
	}
}

function goto(url) {
	processing();
	window.location.href = url;
}

function goback(back_index) {
	if(typeof back_index == "undefined") {
		back_index = -1;
	}

	processing();
	window.history.go(back_index);
}



function getAbsolutePos(el) {
	var SL = 0, ST = 0;
  	var is_div = /^div$/i.test(el.tagName);
  	if (is_div && el.scrollLeft)
  		SL = el.scrollLeft;
  	if (is_div && el.scrollTop)
  		ST = el.scrollTop;
  	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
  	if (el.offsetParent) {
  		var tmp = this.getAbsolutePos(el.offsetParent);
  		r.x += tmp.x;
  		r.y += tmp.y;
  	}
  	return r;
}

function is_email(email) {
	return /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/.test(email);
}

// -------------------------------- javascript extension -------------------------------- //

String.prototype.trim = function () {
  return Trim(this);
}

function Trim(s) {
	s = s.replace(/(^\s+)|(\s+$)/g, "");
	return s
}

// -------------------------------- javascript extension -------------------------------- //


/**
 *	common functions for any application
 */

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function isNotFilled(elm) {
	return ((typeof elm == "undefined" || Trim(elm.value) == "" || Trim(elm.value) == null)) ? true : false;
}

function empty( mixed_var ) {
	var key;

    if (mixed_var === ""
        || mixed_var === 0
        || mixed_var === "0"
        || mixed_var === null
        || mixed_var === false
        || mixed_var === undefined
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            if (typeof mixed_var[key] !== 'function' ) {
                return false;
            }
        }
        return true;
    }
    return false;
}

function is_array() {
	  if (!mixed_var) {
         return false;
     }

     if (typeof mixed_var === 'object') {
         // Uncomment to enable strict JavsScript-proof type checking
         // This will not support PHP associative arrays (JavaScript objects), however
         // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
         //
         //  if (mixed_var.propertyIsEnumerable('length') || typeof mixed_var.length !== 'number') {
         //      return false;
         //  }

         return true;
     }
}

function is_null(val) {
	return (typeof val == "undefined" || val == null ) ? true : false;
}

function checkAll(isCheckedAll, form_checkbox_name) {
	var checkboxs = document.getElementsByName(form_checkbox_name);

	if(typeof checkboxs == "undefined") return;
	if(checkboxs.length) {
	    for(var i = 0, cb; cb = checkboxs[i]; i++)
	      cb.checked = isCheckedAll;
	} else {
	    checkboxs.checked = isCheckedAll;
	}

}

function adjustCheckAll(form_checkbox_name, form_checkAll_name) {

	var checkboxs = document.getElementsByName(form_checkbox_name);
	var checkAll = document.getElementById(form_checkAll_name);

	if(checkboxs.length) {
	    // 多個checkbox的處理
	    for(var i = 0, cb; cb = checkboxs[i]; i++) {
	      if(cb.checked) {
	        continue;
	      } else {
	        checkAll.checked = false;	// 只要有一個沒有勾選，全選的勾勾就要拿掉
	        return;
	      }
	    }
	    checkAll.checked = true;
	} else {
	    // 1個checkbox的處理
	    checkAll.checked = checkboxs.checked;
	    return ;
	}
}

function form_multi_check(form_id, checkbox_name) {
	var form = document.getElementById(form_id);
	if(typeof form[checkbox_name] == "undefined") {
		return false;
	}

	if(form[checkbox_name].length) {
		for(var i= 0, cb; cb = form[checkbox_name][i]; i++) {
       		hasChecked = cb.checked;
       		if(hasChecked)
         			break
       		else
         		continue;
     	  	}
  	} else {
     		hasChecked = form[checkbox_name].checked;
   	}
	return  hasChecked;
}

/**
 * @author Jon Davis <jon@jondavis.net>
 * @version 1.3.1
 */
var using = window.using = function( scriptName, callback, context ) {
    function durl(sc) {
        var su = sc;
        if (sc && sc.substring(0, 4) == "url(") {
            su = sc.substring(4, sc.length - 1);
        }
        var r = using.registered[su];
        return (!r && (!using.__durls || !using.__durls[su]) &&
                sc && sc.length > 4 && sc.substring(0, 4) == "url(");
    }
    var a=-1;
    var scriptNames = new Array();
    if (typeof(scriptName) != "string" && scriptName.length) {
        var _scriptNames = scriptName;
        for (var s=0;s<_scriptNames.length; s++) {
            if (using.registered[_scriptNames[s]] || durl(_scriptNames[s])) {
                scriptNames.push(_scriptNames[s]);
            }
        }
        scriptName = scriptNames[0];
        a=1;
    } else {
        while (typeof(arguments[++a]) == "string") {
            if (using.registered[scriptName] || durl(scriptName)) {
                scriptNames.push(arguments[a]);
            }
        }
    }

    callback = arguments[a];
    context = arguments[++a];

    if (scriptNames.length > 1) {
        var cb = callback;
        callback = function() {
            using(scriptNames, cb, context);
        }
    }

    var reg = using.registered[scriptName];
    if (!using.__durls) using.__durls = {};
    if (durl(scriptName) && scriptName.substring(0, 4) == "url(") {
        scriptName = scriptName.substring(4, scriptName.length - 1);
        if (!using.__durls[scriptName]) {
            scriptNames[0] = scriptName;
            using.register(scriptName, true,  scriptName);
            reg = using.registered[scriptName];
            var callbackQueue = using.prototype.getCallbackQueue(scriptName);
            var cbitem = new using.prototype.CallbackItem(function() {
                using.__durls[scriptName] = true;
            });
            callbackQueue.push(cbitem);
            callbackQueue.push(new using.prototype.CallbackItem(callback, context));
            callback = undefined;
            context = undefined;
        }
    }
    if (reg) {

        // load dependencies first
        for (var r=reg.requirements.length-1; r>=0; r--) {
            if (using.registered[reg.requirements[r].name]) {
                using(reg.requirements[r].name, function() {
                    using(scriptName, callback, context);
                }, context);
                return;
            }
        }

        // load each script URL
        for (var u=0; u<reg.urls.length; u++) {
            if (u == reg.urls.length - 1) {
                if (callback) {
                    using.load(reg.name, reg.urls[u], reg.remote, reg.asyncWait,
                        new using.prototype.CallbackItem(callback, context));
                } else {
                    using.load(reg.name, reg.urls[u], reg.remote, reg.asyncWait);
                }
            } else {
                using.load(reg.name, reg.urls[u], reg.remote, reg.asyncWait);
            }
        }

    } else {
        var cb = callback;
        if (cb) {
            cb.call(context);
        }
    }
}

using.prototype = {

    CallbackItem : function(_callback, _context) {
        this.callback = _callback;
        this.context = _context;
        this.invoke = function() {
            if (this.context) this.callback.call(this.context);
            else this.callback();
        };
    },

	Registration : function(_name, _version, _remote, _asyncWait, _urls) {
	    this.name = _name;
	    var a=0;
	    var arg = arguments[++a];
	    var v=true;
	    if (typeof(arg) == "string") {
	        for (var c=0; c<arg.length; c++) {
	            if ("1234567890.".indexOf(arg.substring(c)) == -1) {
	                v = false;
	                break;
	            }
	        }
	        if (v) {
	            this.version = arg; // not currently used
	            arg = arguments[++a];
	        } else {
	            this.version = "1.0.0"; // not currently used
	        }
	    }
	    if (arg && typeof(arg) == "boolean") {
	        this.remote = arg;
	        arg = arguments[++a];
	    } else {
	        this.remote = false;
	    }
	    if (arg && typeof(arg) == "number") {
	        this.asyncWait = _asyncWait;
        } else {
            this.asyncWait = 0;
        }
	    this.urls = new Array();
	    if (arg && arg.length && typeof(arg) != "string") {
	        this.urls = arg;
	    } else {
	        for (a=a; a<arguments.length; a++) {
	            if (arguments[a] && typeof(arguments[a]) == "string") {
	                this.urls.push(arguments[a]);
	            }
	        }
	    }
	    this.requirements = new Array();
	    this.requires = function(resourceName, minimumVersion) {
	        if (!minimumVersion) minimumVersion = "1.0.0"; // not currently used
	        this.requirements.push({
	            name: resourceName,
	            minVersion: minimumVersion // not currently used
	            });
	        return this;
	    }
	    this.register = function(name, version, remote, asyncWait, urls) {
	        return using.register(name, version, remote, asyncWait, urls);
	    }
	    return this;
	},

    register : function(name, version, remote, asyncWait, urls) {
        var reg;
        if (typeof(name) == "object") {
            reg = name;
            reg = new using.prototype.Registration(reg.name, reg.version, reg.remote, reg.asyncWait, urls);
        } else {
            reg = new using.prototype.Registration(name, version, remote, asyncWait, urls);
        }
        if (!using.registered) using.registered = { };
        if (using.registered[name] && window.console) {
            window.console.log("Warning: Resource named \"" + name + "\" was already registered with using.register(); overwritten.");
        }
        using.registered[name] = reg;
        return reg;
    },

	wait: 0,

	defaultAsyncWait: 250,

	getCallbackQueue: function(scriptUrl) {
		if (!using.__callbackQueue) {
			using.__callbackQueue = {};
		}
 		var callbackQueue = using.__callbackQueue[scriptUrl];
 		if (!callbackQueue) {
 		    callbackQueue = using.__callbackQueue[scriptUrl] = new Array();
 		}
 		return callbackQueue;
	},

	load: function(scriptName, scriptUrl, remote, asyncWait, cb) {
		if (asyncWait == undefined) asyncWait = using.wait;
		if (remote && asyncWait == 0) asyncWait = using.defaultAsyncWait;

		if (!using.loadedScripts) using.loadedScripts = new Array();

 		var callbackQueue = using.prototype.getCallbackQueue(scriptUrl);
 		callbackQueue.push(new using.prototype.CallbackItem( function() {
 		    using.loadedScripts.push(using.registered[scriptName]);
 		    using.registered[scriptName] = undefined;
 		}, null));
 		if (cb) {
 		    callbackQueue.push(cb);
 		    if (callbackQueue.length > 2) return;
 		}
 		if (remote) {
 		    using.srcScript(scriptUrl, asyncWait, callbackQueue);
 		} else {
			var xhr;
			if (window.XMLHttpRequest)
				xhr = new XMLHttpRequest();
			else if (window.ActiveXObject) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xhr.onreadystatechange = function(){
				if (xhr.readyState == 4 && xhr.status == 200) {
					using.injectScript(xhr.responseText, scriptName);
					if (callbackQueue) {
					    for (var q=0; q<callbackQueue.length; q++) {
					        callbackQueue[q].invoke();
					    }
					}
					using.__callbackQueue[scriptUrl] = undefined;
				}
			};
			if (asyncWait > 0 || callbackQueue.length > 1) {
			    xhr.open("GET", scriptUrl, true);
			} else {
			    xhr.open("GET", scriptUrl, false);
			}
			xhr.send(null);
 		}
	},

	genScriptNode : function() {
		var scriptNode = document.createElement("script");
		scriptNode.setAttribute("type", "text/javascript");
		scriptNode.setAttribute("language", "JavaScript");
		return scriptNode;
	},
	srcScript : function(scriptUrl, asyncWait, callbackQueue) {
		var scriptNode = using.prototype.genScriptNode();
		scriptNode.setAttribute("src", scriptUrl);
		if (callbackQueue) {
		    var execQueue = function() {
				using.__callbackQueue[scriptUrl] = undefined;
			    for (var q=0; q<callbackQueue.length; q++) {
			        callbackQueue[q].invoke();
			    }
			    callbackQueue = new Array(); // reset
		    }
			scriptNode.onload = scriptNode.onreadystatechange = function() {
				if ((!scriptNode.readyState) || scriptNode.readyState == "loaded" || scriptNode.readyState == "complete" ||
					scriptNode.readyState == 4 && scriptNode.status == 200) {
					if (asyncWait > 0) {
						setTimeout(execQueue, asyncWait);
					}
					else {
						execQueue();
					}
				}
			};
		}
		var headNode = document.getElementsByTagName("head")[0];
		headNode.appendChild(scriptNode);
	},
	injectScript : function(scriptText, scriptName) {
		var scriptNode = using.prototype.genScriptNode();
		try {
		    scriptNode.setAttribute("name", scriptName);
		} catch (err) { }
		scriptNode.text = scriptText;
		var headNode = document.getElementsByTagName("head")[0];
		headNode.appendChild(scriptNode);
	}
};
using.register = using.prototype.register;
using.load = using.prototype.load;
using.wait = using.prototype.wait;
using.defaultAsyncWait = using.prototype.defaultAsyncWait;
using.srcScript = using.prototype.srcScript;
using.injectScript = using.prototype.injectScript;


/**************** feedback *******************************/
function cancelBubble(evt) {
  	var e = (window.event) ? window.event : evt;
  	e.cancelBubble = true;
  }

function openRemote(url, wname, params) {

	var width = params['width'] || 780;
	var height = params['height'] || 550;

	var scrollbars = params['scrollbars'] || 'yes';
	var resizeable = params['resizeable'] || 'yes';
	var status = params['status'] || 'no';

	var x = (screen.width - width)/2;
  	var y = (screen.height - height)/2;
	var remote = window.open(url, wname,
		 "width="+width+", height="+height+", left="+x+", top="+y+", scrollbars="+scrollbars+", resizable="+resizeable+", status="+status+"");

	if(remote) remote.focus();
	return remote;
}

function unprocessing() {

	var obj = document.getElementById("processing_message");
	if(obj != null) {
		obj.style.display = "none";
	}
}


function show_tab(obj) {

    var tab_id = obj.id;
	var content_id = $("#"+tab_id).attr("content_id");

	var tab_selected = 'point';
	var tab_cleaned = '';

	$("#"+tab_id).parents("ul").children("li").each(function(){

		$(this).removeClass(tab_selected).addClass(tab_cleaned);

		$(this).find("a").each(function(){
			var content_id = $(this).attr("content_id");
			$("#"+content_id).hide();
		});
	});

	$("#"+tab_id).parents("li:first").addClass(tab_selected);

	// 如果 olivia 使用原來的作法
	// $("#"+tab_id).parents("li:first").prev().find("div:nth-child(3)").removeClass("btn_r").addClass("btn_r_n");
	// $("#"+tab_id).parents("li:first").prev().prev().find("div:nth-child(3)").removeClass("btn_r_n").addClass("btn_r");
	// $("#"+tab_id).parents("li:first").find("div:nth-child(3)").removeClass("btn_r_n").addClass("btn_r");

	// 讀取 url
	var content_url = $("#"+tab_id).attr("content_url");
	if(typeof content_url != "undefined" && content_url != "") {
		if($("#"+content_id).html() == "") {

			$("#"+content_id).html("<img src='/public/images/indicator.gif'>");
			$.get(content_url, { t: new Date().getTime() }, function(data){
				$("#"+content_id).html(data);
			});
		}
	}

	$("#"+content_id).show();
}

// requirement: jquery 與 form plugin
/*
使用方法:

using("form", function(){
	// 強制 is_dirty
	<?php if(validation_errors() != ''): ?>
		jQuery("#card_form").attr("is_dirty", "1");
	<?php else: ?>
		jQuery("#card_form").attr("init_string", jQuery("#card_form").formSerialize());
	<?php endif; ?>
});

$(document).ready(function(){
	jQuery("#forward_event_form").attr("init_string", jQuery("#forward_event_form").formSerialize());
});

window.onbeforeunload = function() {
	var forms = $("#TB_window").find("form");
	for(var i = 0; i < forms.length; i++) {
		var query_string = jQuery("#"+forms[i].id).formSerialize();
		var init_string = jQuery("#"+forms[i].id).attr("init_string");
		if( (init_string && query_string !== init_string) || jQuery("#"+forms[i].id).attr("is_dirty") == "1" ) {
			return "所做的變更不會儲存";
		}
	}
}

window.onbeforeunload = function() {
	var query_string = jQuery("#profile_form").formSerialize();
	var init_string = jQuery("#profile_form").attr("init_string");
	if( (init_string && query_string !== init_string) || jQuery("#profile_form").attr("is_dirty") == "1" ) {
		return "所做的變更不會儲存";
	}

	// 視情況作不同判斷
	if( (init_string && query_string !== init_string) && jQuery("#profile_form").attr("no_tip") != "1" ) {
		return "所做的變更不會儲存";
	}
}

beforeSubmit : function() {
	jQuery("#forward_event_form").attr("no_tip", "1");
	$("#submit").append("<img src='<?=image_tag('indicator.gif')?>'/>").attr("disabled","disabled");
},
*/


