/* WZD */

function $C(n, i, c, s) {
    var e;
    e = document.createElement(
        n ? (n.tagName ?
            {
                div: 'div',
                span: 'span',
                table: 'tr',
                tr: 'td',
                ul: 'li',
                ol: 'li',
                dl: 'dd'
            }[n.tagName.toLowerCase()] :
            n
        ) : 'span'
    );
    i && (e.id = i);
    c && (e.className = c);
    s && (e.innerHTML = s);
    return $(e);
}

var Utils = {

    createStyleSheet: function() {
        try {
            //this.currentStyleSheet = null; // todo : garbage collecting
            var styleSheet = document.createElement('STYLE');
            document.documentElement.firstChild.appendChild(styleSheet);
            var length = document.documentElement.getElementsByTagName('style').length - 1;
            this.currentStyleSheet = document.styleSheets(length);
        } catch (e) {
            if (confirm(WZD.I18n.local.IE6ReloadPage)) {
                location.reload();
            }
            this.addStylesheet = Prototype.emptyFunction;
        }
    },

    addStylesheet: function(href) {
        if (document.createStyleSheet) { // fucking IE
            if (this.currentStyleSheet == null) {
                this.createStyleSheet();
            }

            try {
                this.currentStyleSheet.addImport(href);
            } catch (e) {
                this.createStyleSheet();
                this.currentStyleSheet.addImport(href);
            }

        } else { // standard
            var ss = $C('link');
            ss.type = 'text/css';
            ss.rel = 'stylesheet';
            ss.href = href;
            ss.media = 'screen';
            document.documentElement.firstChild.appendChild(ss);
        }
    }
};

// widget
var widget = {

    // callbacks
    onLoad: function() {},
    onRefresh: function() {},
    onResize: function() {},
    onUpdateTitle: function() {},

    // functions
    log: function() {
        var el = $('wzdLog');
        if (el)
            el.value += $A(arguments).join(';').escapeHTML() + '\n';
        else
            debug($A(arguments).join(';').toString());
    },

    getTitle: function() {
        //return $('wzdTitle').value;
        return document.title;
    },

    setTitle: function(s) {
        //$('wzdTitle').value = document.title = s;
        document.title = s;
    },

    getValue: function(n) {
        var fields = $(document.forms[0]).getElements();
        var i = fields.length;
        while (i--) {
            var field = fields[i];
            if (field.name == n) {
                if (field.tagName == 'SELECT') {
                    return field.options[field.selectedIndex].value;
                } else if (field.type == 'checkbox') {
                    return field.checked;
                } else {
                    return field.value;
                }
            }
        }
    },

    setValue: function(n, v) {
        var fields = $(document.forms[0]).getElements();
        var i = fields.length;
        while (i--) {
            var field = fields[i];
            if (field.name == n) {
                if (field.tagName == 'SELECT') {
                    for (var j = field.options.length; j--; ) {
                        if (field.options[j].value == v) {
                            field.options[j].defaultSelected = field.options[j].selected = true;
                            break;
                        }
                    }
                } else if (field.type == 'checkbox') {
                    field.checked = !!v;
                } else {
                    field.value = v;
                }
                break;
            }
        }
    },
	
	getInstanceId : function() {
		return 0;
	},
	
	getWidgetId : function() {
        return 0;
    },
	
	getExecuteURI : function() {
        return location.href;
    },
	
	getExecuteHost : function() {
        return location.host;
    },

    createElement: function(t) {
        return $(document.createElement(t));
    },

    openURL: function(u) {
        window.open(u).focus();
    },
    
    setMsg: function(id, msg) {},

    body: null,
    lang: navigator.language || navigator.browserLanguage || 'ko',
    locale: 'KR'
};


// WZDAPI
var WZD = {

    WZDAPI: {}
};


// emulator
// initialization
var getValueFromSearch = function(name) {
    var name = name.escapeHTML();
    var pat = name + '=([\\w%\+\.\*\-]+)[&#]?';
    var regex = new RegExp(pat);
    var a = '';
    if( a = document.location.search.match(regex)) {
       return decodeURIComponent(a[1]) || '';
    }
};

var startEmulator = function() {

    Utils.addStylesheet('http://external.wzdapi.com/css/v1.5/emulator.css');

    // meta infomation
    var meta = {};
    var nodes = document.getElementsByTagName('meta');
    for (var i = 0; i < nodes.length; i++) {
        var name = nodes[i].name;
        if (!name) continue;
        if ('wkey' == name || 'apiVersion' == name) continue;
        meta[name] = nodes[i].getAttribute('content');
    }
    
    // icon
    var nodes = document.getElementsByTagName('link');
    for (var i = 0; i < nodes.length; i++) {
        var name = nodes[i].rel;
        if (!name) continue;
        if ('icon' == name || 'thumbnail' == name
                || 'screenshot' == name || 'stylesheet' == name) continue;
        meta[name] = nodes[i].href;
    }
    
    // title
    var nodes = document.getElementsByTagName('title');
    meta['title'] = (0 < nodes.length) ? nodes[0].innerHTML : '';
    
    // meta infomation panel
    var metaTokens = [];
    metaTokens.push('<tr><th>이름</th><td>' + meta.title + '</td></tr>');
    metaTokens.push('<tr><th>설명</th><td>' + meta.description + '</td></tr>');
    metaTokens.push('<tr><th>태그</th><td>' + meta.keyword + '</td></tr>');
    metaTokens.push('<tr><th>이미지[리치]</th><td><img src="' + meta.richicon + '" /></td></tr>');
    metaTokens.push('<tr><th>제작자[이름]</th><td>' + meta.author + '</td></tr>');
    metaTokens.push('<tr><th>제작자[이메일]</th><td>' + meta.email + '</td></tr>');
    metaTokens.push('<tr><th>제작자[웹사이트]</th><td>' + meta.website + '</td></tr>');

    // size를 지정하지 않으면, 기본 사이즈로 설정합니다. 
    var width = getValueFromSearch('_width') || meta.width || 200;
    var height = getValueFromSearch('_height') || meta.height || 300;

    // preferences
    var prefTokens = [];
    var prefConts = document.getElementsByTagName('widget:preferences');
    if (!prefConts.length) {
        prefConts = document.getElementsByTagName('preferences');
    }
    if (prefConts.length) {
        var prefs = document.getElementsByTagName('widget:preference');
        if (!prefs.length) {
            var prefs = document.getElementsByTagName('preference');
        }
        for (var i = 0; i < prefs.length; i++) {
            var pref = prefs[i];
            var name = pref.getAttribute('name');
            if (!name)
                continue;
            var type = pref.getAttribute('type') || 'text';
            var label = pref.getAttribute('label') || name;
            var defaultValue = getValueFromSearch(name) || pref.getAttribute('defaultValue') || '';
            switch (type) {
                case 'weather.location':
                case 'date.calendar':
                case 'color':
                case 'text':
                    prefTokens.push('<tr><th>' + label + '</th><td><input type="text" name="' + name.escapeHTML() + '" value="' + defaultValue + '" /></td></tr>');
                    break;
                case 'boolean':
                    prefTokens.push('<tr><th>' + label + '</th><td><input type="checkbox" name="' + name.escapeHTML() + '"' + (defaultValue == 'true' ? ' checked="checked"' : '') + ' value="true" /></td></tr>');
                    break;
                case 'hidden':
                    prefTokens.push('<input type="hidden" name="' + name.escapeHTML() + '" value="' + defaultValue.escapeHTML() + '" />');
                    break;
                case 'range':
                    var min = ~~pref.getAttribute('min');
                    var max = ~~pref.getAttribute('max');
                    var step = ~~pref.getAttribute('step');
                    var options = [];
                    for (; min <= max; min += step) {
                        options.push('<option value="' + min + '"' + (min == defaultValue ? ' selected="selected"' : '') + '>' + min + '</option>');
                    }
                    prefTokens.push('<tr><th>' + label + '</th><td><select name="' + name.escapeHTML() + '">' + options.join('') + '</select></td></tr>');
                    break;
                case 'list':
                case 'list.image':
                    var options = [];
                    var optionNodes = pref.getElementsByTagName('widget:option');
                    if (!optionNodes.length) {
                        optionNodes = pref.getElementsByTagName('option');
                    }
                    for (var j = 0; j < optionNodes.length; j++) {
                        var value = optionNodes[j].getAttribute('value').escapeHTML(); 
                        var label = optionNodes[j].getAttribute('label').escapeHTML();
                        options.push('<option value="' + value + '"' + (value == defaultValue ? ' selected="selected"' : '') + '>' + label + '</option>');
                    }
                    prefTokens.push('<tr><th>' + label + '</th><td><select name="' + name.escapeHTML() + '">' + options.join('') + '</select></td></tr>');
                    break;
                case 'password':
                    prefTokens.push('<tr><th>' + label + '</th><td><input type="password" name="' + name.escapeHTML() + '" value="' + defaultValue.escapeHTML() + '" /></td></tr>');
                    break;
                case 'textarea':
                    prefTokens.push('<tr><th>' + label + '</th><td><textarea name="' + name.escapeHTML() + '">' + defaultValue.escapeHTML() + '</textarea></td></tr>');
                    break;
                default:
                    prefTokens.push('UNKNOWN preference type: ' + type + ' (label: ' + label + ')');
            }
        }
    }
    
    // build preference panel
    var prefSize = '<tr><th>크기</th><td><input class="size" type="text" name="_width" value="' + width + '" /> x <input class="size" type="text" name="_height" value="' + height + '" /></td></tr>';
    var prefHTML = '<table>' + prefSize + prefTokens.join('') + '<tr><th>&nbsp;</th><td><input type="submit" value="적용" /></td></table>';

    // rebuild body
    document.body.innerHTML =  
        '<div class="information_container"><div class="WZDInformationsCon"><h2>기본정보</h2><table id="wzdInformations">' + metaTokens.join('') + '</table></div>' +
        '<div class="WZDPreferencesCon"><h2>설정</h2><form id="wzdPreferences" action="#">' + prefHTML + '</form></div></div>' + 
        
        '<div class="widget_container"><div class="WZDWidgetCon"><h2>위젯</h2><div id="wzdWidget" class="WZDWidget"><div id="wzdContent" class="WZDContent">' +
        '<div id="wzdContainer" class="WZDContainer">' +
        '<div class="WZDLoading" style="display:none;"><img src="http://external.wzdapi.com/images/v1.5/wait_loading.gif" /></div>' +
        '<div class="WZDError" style="display:none;"></div>' +
        '<div id="wzdBody" class="WZDBody ' + document.body.className + '">' + document.body.innerHTML + 
        '</div></div></div></div></div></div>' +
        
        '<div class="log_container"><div class="WZDLogCon"><h2>로그</h2><textarea id="wzdLog" readonly="readonly"></textarea></div></div>';
        

    document.body.className = '';
    widget.body = $('wzdBody');

    // widget resize
    width && (widget.body.style.width = width + 'px');
    height && (widget.body.style.height = height + 'px');

    // editing the title

    // run the widget
    try {
        setTimeout(function() {
            widget.onLoad();
            var size = getSize(widget.body);
            widget.log('widget.onLoad');
            widget.onResize(size.width, size.height);
            widget.log('widget.onResize');
        }, 500);
    } catch (e) {
        widget.log('EXCEPTION: ' + e.file + ': ' + (e.line || e.lineNumber) + ': ' + e.message);
    }

    (meta.autoRefresh = parseInt(meta.autoRefresh)) > 0 && setInterval(function() {
        widget.onRefresh();
    }, meta.autoRefresh * 60000);
};

function getSize(target) {
    var size = {width: parseFloat(target.style.width), height: parseFloat(target.style.height)};
    if ( ! size.width || size.width == NaN) {
        var dim = $(target).getDimensions();
        size.width = dim.width;
        size.height = dim.height;
    }
    return size;
};


/* javascript load */

function loadJavascript(urls, callback, charset) {
    
    var loading = urls.length;
    
    var head= document.getElementsByTagName('head')[0];
    for (var i = 0; i < urls.length; i++) {
        var url = urls[i] + '?rev=1';
        
        var script= document.createElement('script');
        
        script.onreadystatechange= function () {
            if (this.readyState == 'loaded' || this.readyState == 'complete') {
                // load complete
                if (this.loaded) {
                    alert('second occure onreadystatechange');
                    return;
                }
                this.loaded = true;
                loading--;
                if (0 == loading) {
                    callback();
                }
            }
        }
        script.onload = function () {
            // load complete
            loading--;
            if (0 == loading) {
                callback();
            }
        }
        
        script.type= 'text/javascript';
        script.charset = "utf-8";
        script.src = url;
        head.appendChild(script);
    }
};

window.onload = startEmulator;

//window.onload = function() {
//    loadJavascript(['http://external.wzdapi.com/scripts/widget_v1_5.js'], startEmulator);
//    /*loadJavascript(['http://external.wzdapi.com/scripts/lib/prototype-1.5.1.1.js', 
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.Data.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.Drawer.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.DropDown.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.Error.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.List.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.Loading.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.Pager.js',
//                    'http://external.wzdapi.com/scripts/v1.5/WZDAPI.UI.TabView.js'], startEmulator);*/
//};

/*window.onresize = function() {
    setTimeout(function() {
        var size = getSize(widget.body);
        widget.onResize(size.width, size.height);
        widget.log('widget.onResize');
    }, 600);
};*/
widget.getSize = function() {
    return getSize(widget.body);
};

WZDAPI.Data.DEV_MODE = true;