/**
 * @fileOverview DeliMap
 */
;(function(window,$,swfobject,JSON){

/** @private */
var usedRandom = {};
var _dispatcher = $({});
var wrote = false;

var RELOAD_INTERVAL = 10*60*1000;
var CLOSE_STATUS = "delimap_closed_status";

function randomString(length) {
	length = length || 10;
	var A=65,Z=90;
	var fc = function(a,b) {
		var c = String.fromCharCode(a);
		return b ? c.toUpperCase():c.toLowerCase();
	}
	do {
		var r = "",c,i;
		while(r.length<length) {
			i = A+Math.floor((Z-A)*Math.random())+(i>Z?0:10);
			c = i>Z?String(i-Z-1):fc(i,Math.random()<0.5);
			if(c&&r[r.length-1]!=c) r+=c;
		}
	} while(usedRandom[r]);
	usedRandom[r] = true;
	return r
}
function parseQuery(search) {
    search = search || (document.location.search||"").replace(/^\?/,"");
    var ret = {};
    if(!search) return ret;
    var search = search.split("&");
    for(var i=0;i<search.length;++i) {
        var kv = search[i].split("=");
        ret[kv[0]] = kv[1];
    }
    return ret;
}

function bind(type,target) {
    _dispatcher.bind(type,target);
}

function unbind(type,target) {
    _dispatcher.unbind(type,target);
}

function dispatchEvent(e) {
    _dispatcher[0].type = e.type;
    _dispatcher[0].data = e.data;
    _dispatcher.trigger(e.type,[e]);
}

/**
 * @namespace
 * @required swfobject, jQuery, JSON
 */
var delimap = {
    /**
     * @type String
     * @default /lib/swf/delimap.swf
     */
    swfPath : "/lib/swf/delimap.swf",
    /**
     * @type String
     * @default /lib/swf/delimap.resources/
     */
    resourceModulePath : "/lib/swf/delimap.resources/",
    /**
     * @type int
     * @default 380
     */
    height : 380,
    /**
     * @type String
     * @default 9.0
     */
    version : "9.0",
    /**
     * @type String
     * @default delimap-minimized-content
     */
    minimizedDivId : "delimap-minimized-content",
    /**
     * @type String
     * @default delimap
     */
    divId : "delimap",
    /**
     * @type String
     * @default /lib/swf/expressInstall.swf
     */
    expressInstallSwf : "/lib/swf/expressInstall.swf",
    /**
     *
     */
    bind : bind,
    /**
     *
     */
    unbind : unbind
};


/** 
 * @class
 * @name delimap.Event
 */
function Event(type,data) {
    this.type = type;
    this.data = data;
}

/**
 * EventType
 * @type String */
Event.LOGIN_SUCCESS = "login_success";
/**
 * EventType
 * @type String */
Event.LOGIN_FAIL    = "login_fail";
/**
 * EventType
 * @type String */
Event.CLOSE = "delimap_close";
/**
 * EventType
 * @type String */
Event.CHANGE_MODE = "delimap_change_mode"
/**
 * EventType
 * @type String */
Event.LOCATION_UPDATE = "delimap_location_update"

delimap.Event = Event;

/**
 * @name delimap.config
 * @param {Map&lt;String,Object&gt} obj
 */

function setStatus(obj) {
    status = $.extend(status,obj);
    delimap.status = status;
}
delimap.setStatus = setStatus;
/** @private  */
var defaultStatus = {
    lang : "ja",
    user : {
      authorized : false, name : "",
      location : { lat : "", lng : "", zip : ["",""], address : "" }
    },
    tabFocus : 0
}
var status = defaultStatus;
delimap.status = status;

function callbackFn(type,data) {
    dispatchEvent(new Event(type,data));
}

function makeNameSpace(nsPrefix,callback) {
    nsPrefix = nsPrefix || "delimap_";
    callback = callback || callbackFn;
    do {
        var ns = nsPrefix+randomString();
    } while(window[ns]);
    var obj = window[ns] = callback;
    return ns;
}

function getAPIKey() {
    var q = parseQuery(($("script[src*=delimap.js]").attr("src")||"").split("?")[1]||"");
    if(q.key) return q.key;
    var h = document.location.host;
    if(/^tst2/.test(h))
    	return "ABQIAAAAYCG3RoxSCo8pIGqHGdC0kxQU7sO9ydDHvzhc82vboZDuEdqwdBT_W2Tr9pjgCfkBLM7Bm3miNZIPkA";
    if(/\.local$/.test(h))
    	return "ABQIAAAAYCG3RoxSCo8pIGqHGdC0kxS3-KqT4p4AfLL9uDmougYsthSUphSetNHRiu0UPVwjTnsgrv1gJTORLA";
}

function close() {
    var swf = $("#"+delimap.divId);
    var div = swf.parent();
    swf.remove();
    div.append("<div id=\""+delimap.divId+"\" style=\"display:none;\" />");
    wrote = false;
    var minidiv = $("#"+delimap.minimizedDivId);
    delimap.unbind(delimap.Event.LOGIN_SUCCESS,reload);
    delimap.unbind(delimap.Event.LOCATION_UPDATE,reload);
    delimap.unbind(delimap.Event.CLOSE,close);
    delimap.unbind(delimap.Event.CHANGE_MODE,changeMode);
    minidiv.css("display","block");
    $.cookie(CLOSE_STATUS,"1",{ path : "/" });
    div.animate({
        height : minidiv.height()+"px"
    });
}

function open() {
    var swf = $("#"+delimap.divId);
    var div = swf.parent();
    var minidiv = $("#"+delimap.minimizedDivId);
    minidiv.css("display","none");
    swf.css("display","block");
    $.cookie(CLOSE_STATUS,"0",{ path : "/" });
    div.animate({
        height : delimap.height
    },function(){
        writeFlash();
    });
}

/** @private */
function handleOnLoad() {
    if($.cookie(CLOSE_STATUS)!="1") {
        writeFlash();
    } else {
        var minidiv = $("#"+delimap.minimizedDivId);
        minidiv.css("display","block");
        minidiv.parent().css("height",minidiv.height()+"px");
    }
}

function writeFlash() {
    if(wrote) return;
    wrote = true;
    var params = {
        wmode : "opaque"
    };
    var q = parseQuery();
    var nocache = q.nocache == "1";
    var cacheKiller = (nocache?("?"+randomString()):"");
    
    var locale = status.lang == "English" ? "en_US" : "ja_JP";
    var ns = makeNameSpace();
    var flashVars = {
        status : encodeURIComponent(JSON.stringify(status)),
        key : getAPIKey(),
        resourceModuleURLs : encodeURIComponent(delimap.resourceModulePath+locale+".swf"+cacheKiller),
        locale : locale,
        localeChain : locale,
        lang : status.lang,
        debug : q.debug||"",
        console : typeof(window["console"])!="undefined"&&q.console==""?"1":"",
        nocache : nocache?randomString():"",
        callbackName : ns,
        reloadInterval : RELOAD_INTERVAL
    };
    var attributes = {};
    //alert(encodeURIComponent(JSON.stringify(status)));
    swfobject.embedSWF(
        delimap.swfPath+cacheKiller,
        delimap.divId,
        "100%",
        delimap.height,
        delimap.version,
        delimap.expressInstallSwf,
        flashVars,
        params, attributes, callbackFn);
    setTimeout(function(){
        delimap.bind(delimap.Event.LOGIN_SUCCESS,reload);
        delimap.bind(delimap.Event.CLOSE,close);
        delimap.bind(delimap.Event.CHANGE_MODE,changeMode);
        delimap.bind(delimap.Event.LOCATION_UPDATE,reload);
    },10);
}

function changeMode(self,e) {
    var when = e.data.when || 0;
    var requri = "/change_order_mode.php?m="+ when +"&redirect="+encodeURIComponent(document.location.href);
    document.location.assign(requri);
}

function reload() {
    document.location.reload();
}

delimap.close = close;
window.delimap = delimap;
window.openDeliMap = open;

$(handleOnLoad);


})(window,jQuery,swfobject,window["JSON"]);
