(function(){
    $E.onDomload(
        function() {
            Citizen.load();
        }
    );
})();

Citizen = {
    
    curFeature: 1,

    load: function() {
        // new window links
        $U.setNewWindowLinks();
        
        // menu
        new $W.Menu('nav');
        
        // tabs
        Citizen.setTabs();
        
        // model no field
        Citizen.setModelNoField();
        $U.toggleTextfieldMessage('modelNo', 'Model No');
        
        // find a watch
        var faw = $D.id('fawForm'); 
        if (faw) {
            var faw = new Citizen.Findawatch;
            faw.set();
        }
        
        // model zoom
        var model = $D.id('model');
        if (model) {
            Citizen.Model.setZoom();
        }
        
        // global sites
        var global = $D.id('globalSites');
        global.id = 'globalSitesPlus';
        var sites = $D.id('sites');
        sites.id = 'sitesPlus';
        var select = $D.id('globalSelect');
        select.id = 'globalSelectPlus';
        if (global) {
            global.open = false;
            $E.listen(global, 'click', function(e){
                if (global.open) {
                    global.open = false;
                    sites.style.display = 'none';
                    return;
                }
                var target = $E.getTarget(e);
                if (target.tagName != 'A' || !global.open) {
                    $E.kill(e);
                }
                sites.style.display = 'block';
                global.open = true;
                $E.listen($D.tags('body')[0], 'click', function(){
                    sites.style.display = 'none';
                    global.open = false;
                });
            });
        }
        
        // mac stylesheet
        if ((navigator.userAgent.toLowerCase().indexOf("mac") != -1)) {
        	var link  = $D.create('link');
        	link.rel = 'stylesheet';
        	link.type = 'text/css';
        	link.href = '/css/mac.css';
        	$D.tags('head')[0].appendChild(link);
        }
        
        // za special event
        /*if (document.location.host.match("za")) {
            var img = new Image(750, 535);
            img.src = "http://www.citizenwatches.co.za/images/content/special-event.jpg";
            img.onload = function() {
                var eventDiv = $D.create('div', {'id':'eventImage'});
                var close = $D.create('div', {'id':'eventClose'});
                $D.setContent(close, '<span id="close">close X</span>');
                eventDiv.appendChild(close);
                eventDiv.appendChild(this);
                eventDiv.onclick = function() {
                    //this.style.display = 'none';
                };
                $D.id('container').appendChild(eventDiv);
                $F.fadeIn(eventDiv);
                $D.id('close').onclick = function() {
                    eventDiv.style.display = 'none';
                };
            };
        }*/
        
    },
    
    setTabs: function(){
        if ($D.id('tabs')) {
            Citizen.setTab(Citizen.curFeature);
        }
        if ($D.id('t-5') && Citizen.curFeature == 4) {
            Citizen.curFeature = 5;
        }
        if ($D.id('tabs')) {
            $E.listen('tabs', 'click', function(e){
                $E.kill(e);
                var tab = $E.getTarget(e);
                if (tab.tagName == 'A') {
                    var num = tab.id.split('-')[1];
                    Citizen.setTab(num);
                }
            });
        }
    },
    
    setTab: function(num){
        // calculate and set background position of tabs
        var position = (num - 1) * 27;
        if (position > 81) {
            position = 81;
        }
        position == 0 ? position = '0' : position = "-" + position + "px";
        $D.id('tabs').style.backgroundPosition = "0 " + position;
        $D.id('feature-' + Citizen.curFeature).style.display = 'none';
        $D.id('feature-' + num).style.display = 'block';
        $D.id('main-img-' + Citizen.curFeature).id = 'main-img-' + num;
        Citizen.curFeature = num;
    },
    
    setModelNoField: function(){
        var label = $D.id('modelNoLabel');
        var input = $D.id('modelNo');
        label.style.position = 'relative';
        label.style.left = '-999em';
        input.value = 'Model No';
    }
    
};

Citizen.Model = {
    
    setZoom: function() {
        
        var model = $D.getContent('model');
        var button = $D.create('div', {id: 'buttonZoom'});
        $D.setContent(button, "<a href=''><span>Zoom</span></a>");
        $D.insertBefore('images', button);
        $E.listen(button, 'click', function(e){
            $E.kill(e);
            Citizen.Model.show(model);
        });
    },
    
    show: function(model) {
        $F.fadeOut('images');
        $F.fadeOut('details');
        var div = $D.create('div', {id: 'bigWatchImage'});
        var content = "<img src='/images/content/products/models/L/" + model + ".jpg' alt='" + model + "' />";
        content += "<div id='buttonClose'><a href=''><span>Close</span></a></div>";
        $D.setContent(div, content);
        $D.id('content').appendChild(div);
        $F.fadeIn('bigWatchImage');
        $E.listen('buttonClose', 'click', function(e){
            $E.kill(e);
            Citizen.Model.hide(e);
        });
        $D.id('content').style.height = '700px';
    },
    
    hide: function(e){
        $F.fadeOut('bigWatchImage');
        $F.fadeIn('images');
        $F.fadeIn('details');
        $D.id('content').style.height = 'auto';
    }
    
};

Citizen.Findawatch = function() {
    this.curLabel = null;
    this.cookie = new $CK('faw');
    this.qs = null;
    this.state = null;
    this.page = 1;
}

Citizen.Findawatch.prototype = {
    
    set: function() {
        var faw = $D.id('findaForm');
        if (typeof(faw) != undefined) {
            var that = this;
            $E.listen(faw, 'click', function(e){
                var target = $E.getTarget(e);
                if (target.tagName == 'INPUT') {
                    that.highlightLabel(target);
                    $D.setContent('paginator', '&nbsp;');
                    $D.setContent('thumbs', '&nbsp;');
                    $D.appendClass('thumbs', 'loading');
                    that.update();
                }
            });
            $E.listen('paginator', 'click', function(e){
                $E.kill(e);
                var target = $E.getTarget(e);
                if (target.tagName == 'A') {
                    that.page = $D.getContent(target);
                    that.fetchPage();
                }
            });
            if (this.cookie.values.qs && this.cookie.values.state) {
                this.setControls();
                this.fetchPage();
            } else {
                this.buildQs();
                this.fetchResults();
            }
            $E.listen('resetButton', 'click', function(e){
                $E.kill(e);
                var button = $D.id('resetButton');
                button.blur();
                faw.reset();
                that.resetLabels();
                that.update();
            });
            $E.listen('priceOrder', 'click', function(e){
                var target = $E.getTarget(e);
                if (target.tagName == 'INPUT') {
                    $D.setContent('paginator', '&nbsp;');
                    $D.setContent('thumbs', '&nbsp;');
                    $D.appendClass('thumbs', 'loading');
                    that.update();
                }
            });
            $D.id('updateButton').style.display = 'none';
        }
    },
    
    update: function() {
        this.page = 1;
        this.buildQs();
        this.setCookie();
        this.fetchResults();
    },
    
    fetchResults: function() {
        var http = new $H;
        var that  = this;
        http.post('/products/find-your-watch', this.qs, function() {
            that.updateResults(http);
        });
    },
    
    updateResults: function(http) {
        $D.removeClass('thumbs', 'loading');
        if (http.text == '0') {
            $D.setContent('thumbs', '<p>Sorry, there are no watches matching those options. Change your options to see more watches.<p>');
            $D.setContent('total', '&nbsp;');
            $D.setContent('paginator', '&nbsp;');
        } else {
            var results = http.text.split("|");
            $D.setContent('total', 'Watches: ' + results[0]);
            $D.setContent('paginator', results[1]);
            $D.setContent('thumbs', results[2]);
        }
    },    
    
    fetchPage: function() {
        $D.setContent('results', '&nbsp;');
        //$D.appendClass('results', 'loading');
        this.buildQs();
        this.setCookie();
        this.fetchResults();
    },
    
    buildQs: function() {
        var form = $D.id('findaForm'); 
        this.qs = "";
        this.state = "";
        for (var i = 0, len = form.elements.length; i < len; i++) {
            if (form.elements[i].checked) {
                this.qs += form.elements[i].name + "=" + form.elements[i].value + "&";
                this.state += form.elements[i].id + "&";
            }
        }
        this.qs += "page=" + this.page;
        this.state += this.page; 
    },
    
    setCookie: function(qs, state){
        this.cookie.setValue('qs', this.qs);
        this.cookie.setValue('state', this.state);
        this.cookie.setPath('/products/');
        this.cookie.set();
    },
    
    highlightLabel: function(elm){
        if (elm.id.substr(elm.id.length - 3) == 'All') {
            var group = elm.id.substr(0, elm.id.length - 3);
        }else {
            var group = elm.id.substr(0, elm.id.length - 1);
        }
        for (var i = 0; i < 10; i++) {
            if ($D.id(group + i + 'Label')) {
                $D.removeClass('r-' + group + i,'selected');
            }
        }
        if ($D.id('r-' + group + 'All')) {
            $D.removeClass('r-' + group + 'All','selected');
        }
        if ($D.id('r-' + elm.id)) {
            $D.appendClass('r-' + elm.id,'selected');
        }
        
    },
    
    resetLabels: function(){
        var inputs = $D.tags('input', 'fawForm');
        for (var i = 0, len = inputs.length; i < len; i++) {
            var row = inputs[i].parentNode;
            $D.removeClass(row,'selected');
            if (row.id.substr(row.id.length - 3) == 'All') {
                $D.appendClass(row,'selected');
            }
        }
    },
    
    setControls: function(){
        var groups = this.cookie.values.state.split("&");
        for (var i = 0, len = groups.length - 1; i < len; i++) {
            if ($D.id(groups[i])) {
                $D.id(groups[i]).checked = 'checked';
                this.highlightLabel($D.id(groups[i]));
            }
        }
        if (groups[len] >= 1) {
            this.page = groups[len];
        }
    }
    
};
