Object.extend(Position, {
    clientSize: function() {
        return [
            window.innerWidth  || Math.min(document.body.clientWidth,  document.documentElement.clientWidth),
            window.innerHeight || Math.min(document.body.clientHeight, document.documentElement.clientHeight)
        ];
    }
});

/////////////////////////////////////////

var LayerPopup = {
    layer: null,
    
    _blindResize: function() {
        var size = Position.clientSize();
        var dim = {width: 0, height: 0};
        var scrollHeight = !Prototype.Browser.Opera ? Position.realOffset(document.body)[1] : Position.realOffset(document.body)[1] / 2;
        
        var blind = $('wzdBlind');       
        blind.style.height = Math.max($(document.body).getDimensions().height, Math.floor((size[1] / 2) - (dim.height / 2)) + scrollHeight + dim.height) + 'px';
    },
    
    show: function(el) {
        this.layer && this.hide();
        this.layer = el;
        Element.show('wzdBlind');
        this.layer && this.layer.show();
        this._blindResize();
    },
    
    hide : function() {
        Element.hide('wzdBlind');
        this.layer && this.layer.hide();
        this.layer = null;
    }
};

/////////////////////////////////////////

function copytoClipboard(str, message)
{
    if (window.clipboardData) { // for IE
        window.clipboardData.setData('Text', str);
    } else { // other Browser
        var flashcopier = document.getElementById('flashcopier');
        if ( ! flashcopier) {
            flashcopier = document.createElement('div');
            flashcopier.id = 'flashcopier';
            document.body.appendChild(flashcopier);
        }
        var embed = '<embed src="/swf/clipboard.swf" FlashVars="clipboard=' + escape(str) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        flashcopier.innerHTML = embed;
    }
    message = message ? message : 'The code has been copied.';
    alert(message);
}

/////////////////////////////////////////

var WidgetPreferences = {
    init: function() {
       this.initEl();
       this.initSubmit();
       this.initPreferencesEvent();
       this.resetFormValues();
    },
    
    initEl: function() {
        this.form = $('digForm');
        this.layer = $('installWidgetLayer');
    },
    
    initSubmit: function() {
        this.form.observe('submit', function(e) {
            Event.stop(e);
            
            if (!this.validateForm()) {
                return false;
            }
            
            var url = '/layer/async_create';
            new Ajax.Request(url, {
                method: 'POST',
                postBody: this.form.serialize(),
                onSuccess: this.registerSuccess.bind(this),
                onFailure: this.registerFail.bind(this)
            });
        }.bind(this));
    },
    
    registerSuccess: function(res) {
        try {
            scripturl = res.responseText.evalJSON().scripturl;
            InstallWidget.show(scripturl);
        } catch(e) {
            alert('There has been an unexpected error.');
        }
    },
    
    registerFail: function(res) {
        try {
            message = res.responseText.evalJSON().message;
        } catch(e) {
            message = 'There has been an unexpected error.';
        }
        alert(message);
    },
    
    initPreferencesEvent: function() {
        
        var f = this.form;
    
        // list_image
        var elements = f.getElementsByClassName('list_image');
        for (var i = 0, cnt = elements.length; i < cnt; i++) {
            var el = $(elements[i]);
            el.observe('click', function(e) {
                Event.stop(e);
                var target = Event.findElement(e, 'LI');
                var pref = $(target.parentNode);
                $A(pref.getElementsByTagName('li')).each(function(item){
                    Element.removeClassName(item, 'selected');
                });
                Element.addClassName(target, 'selected');
                f[pref.getAttribute('name')].value = target.getAttribute('value');
            }.bind(this));
        }
        
        // size
        var _width = 170;
        var _height = 160;
        f.width.onkeyup = function() {
             f.width.value = f.width.value ? (f.width.value.match(/\d+/g) || []).join('') : '';
             f.height.value = f.width.value ? Math.round(f.width.value * _height / _width) : 0;
        };
        f.width.onblur = function() {
            f.width.value = f.width.value ? f.width.value : 0;
        };
        f.height.onkeyup = function() {
            f.height.value = f.height.value ? (f.height.value.match(/\d+/g) || []).join('') : '';
            f.width.value = f.height.value ? Math.round(f.height.value * _width / _height) : 0;
        };
        f.height.onblur = function() {
            f.height.value = f.height.value ? f.height.value : 0;
        };
        
        // location_search
        $(this.form['preferences[location__city_name]']).observe('click', function(e) {
            LocationSearch.show();
        }.bind(this));
    },
    
    setLocationValue: function(code, name) {
        this.form['preferences[location]'].value = code;
        this.form['preferences[location__city_name]'].value = name;
    },
    
    resetFormValues: function() {
        var f = this.form;

        f.width.value = '170';
        f.height.value = '160';
        
        f['preferences[blog]'].value = 'http://';
        
        f['preferences[nickname]'].value = '';
        
        f['preferences[email]'].value = '';
        
        f['preferences[contents]'].value = 'random';
        var elements = f.getElementsByClassName('list_image');
        for (var i = 0, cnt = elements.length; i < cnt; i++) {
            var el = $(elements[i]);
            $A(el.getElementsByTagName('li')).each(function(item) {
               $(item).removeClassName('selected');
            });
            $(el.getElementsByTagName('li')[0]).addClassName('selected');
        }
        
        
        f['preferences[location]'].value = '';
        f['preferences[location__select]'].value = 'direct';
        f['preferences[location__city_name]'].value = '';
        
        $A(f['preferences[tempunit]']).each(function(item, index) {
            item.checked = item.value == 'f' ? 'checked' : null;
        });
    },
    
    validateForm: function() {
        
        var f = this.form;
        
        if (f.width.value == 0 || f.height.value == 0) {
            alert('Please enter widget size.');
            return false;
        } else if (!f['preferences[blog]'].value.match(/^(https?\:\/\/)([a-zA-Z0-9\_\-]+\.)+([a-zA-Z0-9]+)(\/)?(\S+\/?)*$/)) {
            alert('Please enter blog or website address.\ne.g. http://www.visitkorea.or.kr');
            return false;   
        } else if (f['preferences[nickname]'].value == '') {
            alert('Please enter blog nickname.');
            return false;
        } else if (!f['preferences[email]'].value.match(/^[a-zA-Z0-9\_\-\.]+\@([a-zA-Z0-9\_\-]+\.)+([a-zA-Z0-9]+)$/)) {
            alert('Please enter your e-mail address.\ne.g.) sparkling@mail.com');
            return false;
        } else if (f['preferences[location]'].value == '') {
            alert('Please select a location.');
            return false;
        } 
        
        return true;
    }
};
WidgetPreferences.init();



/////////////////////////////////////////

var InstallWidget = {
    init: function() {
       this.initEl();
       this.initEvent();
    },
    
    initEl: function() {
        this.layer = $('installWidgetLayer');
        this.els = {};
        this.els.code = $('widget_code');
        this.els.copycode = $('copycode_btn');
    },
    
    initEvent: function() {
        this.layer.getElementsByClassName('btnClose')[0].observe('click', function(e) {
            Event.stop(e);
            LayerPopup.hide();
        });
        
        this.els.code.observe('click', function(e) {
            Event.stop(e);
            this.els.code.select();
        }.bind(this));
        
        this.els.copycode.observe('click', function(e) {
            Event.stop(e);
            copytoClipboard($F(this.els.code));
        }.bind(this));
    },
    
    show: function(scriptUrl) {
        LayerPopup.show(this.layer);
        this.els.code.value = '<script type="text/javascript" src="' + scriptUrl + '"></script>';
    }
};
InstallWidget.init();



/////////////////////////////////////////


var LocationSearch = {
    init: function() {
       this.initEl();
       this.initEvent();
    },
    
    initEl: function() {
        this.layer = $('locationSearchLayer');
        this.els = {},
        this.els.searchName = this.layer.getElementsByClassName('search_name')[0];
        this.els.searchBtn = this.layer.getElementsByClassName('search_btn')[0];
        this.els.deleteBtn = this.layer.getElementsByClassName('delete_btn')[0];
        this.els.searchResult = this.layer.getElementsByClassName('search_result')[0];
        this.els.closeBtn = this.layer.getElementsByClassName('btnClose')[0];
    },
    
    initEvent: function() {
        this.els.searchBtn.observe('click', function(e) {
            Event.stop(e);
            this.requestLocationSearch();
        }.bind(this));
        
        this.els.searchName.observe('keydown', function(e) {
            if (e.keyCode == 13) {
                Event.stop(e);
                this.requestLocationSearch();
            }
        }.bind(this));
        
        this.els.deleteBtn.observe('click', function(e) {
            Event.stop(e);
            this.els.searchName.value = '';
            this.els.searchResult.innerHTML = 'Please enter city name.';
        }.bind(this));
        
        this.els.closeBtn.observe('click', function(e) {
            Event.stop(e);
            LayerPopup.hide();
        }.bind(this));
    },
        
    requestLocationSearch: function() {

        if (this.els.searchName.value == '') {
            this.els.searchResult.innerHTML = '<li>Please enter city name.</li>';
            return false;
        }

        this.els.searchResult.innerHTML = '<li>Searching...</li>';
        
        var url = '/proxy/xoap.weather.com/search/search?where=' + encodeURIComponent(this.els.searchName.value);
        new Ajax.Request(url, {
            method: 'GET',
            onSuccess : this.renderLocationSearchResult.bind(this)
        });
    },
        
    renderLocationSearchResult: function(res) {
        this.els.searchResult.innerHTML = '';
        
        var data = res.responseXML;
        
        var locs = data.getElementsByTagName('loc');
        if (locs.length == 0) {
            this.els.searchResult.innerHTML = '<li>There is no such city. Type the exact city name in English.</li>';
            return false;
        }
        
        $A(locs).each(function(item, idx) {
            var id = item.getAttribute('id');
            var name = item.firstChild.nodeValue;
            var li = document.createElement('li');
            
            var a = $(document.createElement('a'));
            a.innerHTML = name;
            a.href = "#";
            a.observe('click', function(e) {
                Event.stop(e);
                WidgetPreferences.setLocationValue(id, name);
                LayerPopup.hide();
            }.bind(this));

            li.appendChild(a);
            this.els.searchResult.appendChild(li);
        }.bind(this));
    },
    
    show: function() {
       LayerPopup.show(this.layer);
    }
};
LocationSearch.init();
