﻿(function($) {
    $.watermark = {
        isActive: false,
        hidden: null
    };
    $.fn.extend({
        watermark: function() {
            this.buildHidden();
            var self = this;
            this.focus(function() {
                self.hidden.hide();
            })
            .blur(function() {
                if ($(this).val() == '') {
                    self.hidden.fadeIn("fast");
                }
            });
            if ($(this).val() == '') {
                self.hidden.fadeIn("fast");
            }
        },
        buildHidden: function() {
            var pos = this.position();
            if (pos == null) return;
            this.hidden = $(document.createElement("label"))
            .css({
                position: "absolute",
                left: pos.left,
                top: pos.top,
                padding: "0.2em"
            })
            .addClass("watermark")
            .attr("for", this.attr("id"))
            .text(this.attr("title"))
            .hide()
            .insertBefore(this);
        }
    });

    $.vote = {
        settings: null
    };
    $.fn.extend({
        vote: function() {
            return new $.Vote(this);
        }
    });
    $.Vote = function(self) {
        var loaderHtml = "<img src='/Content/images/loader.gif' alt='Loading...' />";
        self.find('a.unauthorized').click(function() {
            $('#dialog_unauthorized').dialog('open');
        });
        self.find('a.action').click(function() {
            $.ajax({
                url: $(this).attr("action"),
                cache: false,
                success: function(html) {
                    self.replaceWith(html);
                }
            });
            self.find("div.ticker").html(loaderHtml);
            self.find("div.cast").hide();
        });
        self.find('a.change-vote').click(function() {
            var prevHtml = self.find("div.ticker").html();
            $.ajax({
                url: $(this).attr("action"),
                cache: false,
                success: function(html) {
                    self.find("div.ticker").html(prevHtml);
                    self.find("div.cast").show();
                    $('#dialog_changevote').html(html);
                    $('#dialog_changevote').dialog('open');
                }
            });
            self.find("div.ticker").html(loaderHtml);
            self.find("div.cast").hide();            
        });
    }

    $.ayobaTabs = {
        settings: {
            css: 'tabs',
            corners: true
        },
        container: null,
    };
    $.fn.extend({
        ayobaTabs: function(selected, settings) {
            settings = $.extend({}, $.ayobaTabs.settings, settings);
            container = new $.AyobaTabs(this, selected, settings);
            return this;
        },
        open: function(tab) {
            var ul = $(this).children('ul');
            ul.children('li').each(function(i, item) {
                $(item).children('a[tabid="#' + tab + '"]').each(function(j, tab) {
                    $(tab).click();
                });
            });
        }
    });
    $.AyobaTabs = function(self, selected, settings) {
        self.addClass(settings.css);
        var ul = self.children('ul');
        ul.addClass('tabs-ul');
        if(settings.corners){
            self.addClass('ui-corner-all');
            ul.addClass('ui-corner-all');  
        }
        ul.children('li').each(function(i, item) {
            $(item).addClass('tabs-li');
            if(settings.corners){
                $(item).addClass('ui-corner-top');
            }
            var link = $(item).children('a');
            link.replaceWith('<a tabid="' + link.attr('href') + '" href="javascript:">' + link.html() + '</a>');
            $(item).click(function(e) {
                self.children('div').hide();
                ul.children('li').removeClass('tabs-li-active');
                $(this).addClass('tabs-li-active');
                self.children('#' + link.attr('href')).show();
            });
        });
        ul.append('<li class="tabs-clear"></li>');
        self.children('div').each(function(i, item) {
            $(item).addClass('tabs-content');
            if(settings.corners){
                $(item).addClass('ui-corner-bottom');
            }
            $(item).hide();
        });
        ul.children('li:first').click();
    }

    $.googleMap = {
        canvas: null,
        geocoder: null,
        address: null,
        image: null,
        shadows: null,
        shape: null,
        markers: null,
        activeMarkers: null,
        defaults: {
            selectable: false,
            zoom: [10, 12, 14, 16, 18, 20],
            onSelected: null
        },
        markerDefaults: {
            title: '',
            contentUrl: '',
            style: 0,
            id: null
        }
    };
    $.fn.extend({
        settings: null,
        googleMap: function(settings) {
            this.initialize(settings);
            return this;
        },
        initialize: function(settings) {
            var self = this;
            self.activeMarkers = new Array();
            self.settings = $.extend({}, $.googleMap.defaults, settings);
            self.geocoder = new google.maps.Geocoder();
            self.canvas = new google.maps.Map(document.getElementById(self.attr("id")), {
                zoom: self.settings.zoom[0],
                center: new google.maps.LatLng(-28, 24),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            self.markers = new Array(3);
            self.markers[0] = new google.maps.MarkerImage('/content/images/marker-active.png',
              new google.maps.Size(32, 32),
              new google.maps.Point(0, 0),
              new google.maps.Point(0, 32));
            self.markers[1] = new google.maps.MarkerImage('/content/images/marker-inactive.png',
              new google.maps.Size(32, 32),
              new google.maps.Point(0, 0),
              new google.maps.Point(0, 32));
            self.markers[2] = new google.maps.MarkerImage('/content/images/marker-event.png',
              new google.maps.Size(32, 32),
              new google.maps.Point(0, 0),
              new google.maps.Point(0, 32));              
            self.shadows = new Array(2);
            self.shadows[0] = new google.maps.MarkerImage('/content/images/marker-shadow.png',
              new google.maps.Size(64, 64),
              new google.maps.Point(15, 0),
              new google.maps.Point(0, 48));
            self.shape = {
                coord: [1, 1, 1, 20, 18, 20, 18, 1],
                type: 'poly'
            };
            if (self.settings.selectable) {
                google.maps.event.addListener(self.canvas, 'click', function(event) {
                    self.geocoder.geocode({ 'latLng': event.latLng }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[0]) {
                                if (self.settings.onSelected) {
                                    settings.onSelected(event.latLng, results[0]);
                                }
                            }
                        }
                    });
                });
            }
        },
        addMarkerAt: function(lat, lng, params) {
            this.addMarkerAtLatLng(new google.maps.LatLng(lat, lng), params);
        },
        clearMarkers: function() {
            for(var i=0;i<this.activeMarkers.length;i++){
                this.activeMarkers[i].setMap(null);
            }
            this.activeMarkers = new Array();
        },
        addMarkerAtLatLng: function(latlng, params) {
            var mParams = $.extend({}, $.googleMap.markerDefaults, params);
            var self = this;
            var nmarker = new google.maps.Marker({
                map: self.canvas,
                icon: self.markers[mParams.style],
                shadow: self.shadows[0],
                shape: {
                    coord: [1, 1, 1, 30, 30, 30, 30, 1],
                    type: 'poly'
                },
                zIndex: 99999,
                position: latlng,
                title: mParams.title + ' - Click for more'
            });
            self.activeMarkers.push(nmarker);
            if (mParams.contentUrl != '') {
                google.maps.event.addListener(nmarker, 'click', function() {
                    var info = new google.maps.InfoWindow({
                        content: 'Loading...'
                    });
                    info.open(self.canvas, nmarker);
                    $.get(mParams.contentUrl, function(data) {
                        info.setContent(data);
                    });
                });
            }
        },
        setCenterAt: function(lat, lng, address) {
            var pos = new google.maps.LatLng(lat, lng);
            this.canvas.setZoom(12);
            this.canvas.setCenter(pos);
        },
        showOnMap: function(address) {
            var self = this;
            if (address == '' || address == null) return;
            this.geocoder.geocode({ address: address }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK && results.length) {
                    self.canvas.set_zoom(self.settings.zoom[Math.max(0, address.split(',').length - 1)]);
                    if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                        self.marker.setPosition(results[0].geometry.location),
                        self.canvas.setCenter(results[0].geometry.location);
                    }
                }
            });
        },
        setCenter: function(address) {
            var self = this;
            if (address == '' || address == null) return;
            this.geocoder.geocode({ address: address }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK && results.length) {
                    try{
                    self.canvas.setZoom(self.settings.zoom[Math.max(0, address.split(',').slice(0, 3).length - 1)]);
                    }catch(err){}
                    if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                        self.canvas.setCenter(results[0].geometry.location);
                    }
                }
            });
        }
    });

    $.network = {
        defaults: {
            url: "/networks/search",
            loader: "/Content/images/loader.gif",
            allowEdit: true,
            onAddressSelected: null
        }
    };
    $.fn.extend({
        network: function(settings) {
            settings = $.extend({}, $.network.defaults, settings);
            $.Networker(this, settings);
            return this;
        }
    });

    $.Networker = function(self, settings) {

        var rx = /\b(nid)\s*=\s*"([^"]*)"/g;

        var levels = new Array(10);
        
        var timeout = null;
        
        self.find("div[level]").each(function(i, item) {
            var level = levels[i + 1] = $(item);
            var parent = level.find('input.value').val();
            init(i + 1, level);
            var input = level.children('input[type=text]');
        });
        
        self.find("div.province").each(function(i, level) {
            $(level).children("select").change(function() {
                var value = $(level).find('input.value');
                value.val($(this).val());
                var id = Number($(level).attr('level'));
                levels[id].setOptions({ url: 'test' });
                setParams(levels[id + 1], value.val());
                show();
            });
        });
        
        function resolveParentValue(level) {
            if(!levels[level - 1]) return null;
            return levels[level - 1].children('input.value').val();
        }
        
        function debug(output) {
            $('#ndebug').html($('#ndebug').html() + '<br />' + output);
        }
        
        function getUrl(index, level){
            var url = settings.url + '/?level=' + index;
            return url;
        }
        
        function setParams(level, params) {
            if(level == null) return;
            var input = level.children('input[type=text]');
            input.setOptions({
                extraParams: {
                    parent: params
                }
            });
        }
        
        function init(index, level) {
            if(level == null) return;
            var input = level.children('input[type=text]');
            var id = Number(level.attr('level'));
            input.unautocomplete();
            input.autocomplete(getUrl(index, level), {
                width: 260,
                selectFirst: false,
                formatResult: function(row) {
			        return row[0].replace(/(<.+?>)/gi, '');
		        },
		        extraParams: {
		            parent: levels[id].find("input.value").val()
		        }
            });
            input.result(function(event, data, formatted) {
                event.stopImmediatePropagation();
                var match = rx.exec(data);
                if(match == null) match = rx.exec(data);
                var value = levels[id].find("input.value");
                if(match != null) {
                    value.val('id:' + match[2]);
                    setParams(levels[id + 1], value.val());
                } else {
                    value.val(null);
                }
                show();
            });            
            input.keyup(function(event){
                event.stopImmediatePropagation();
                var value = levels[id].find("input.value");
                value.val('other:' + input.val());
                show();
            });
        }
        
        function show() {
            var address = '';
            self.find('select option:selected').each(function(i, item){
                if($(this).text() != null && $(this).text() != '') {
                   address += $(this).text() + ',';
                }
            });
            self.find('input[type=text]').each(function(i, item) {
                if($(this).val() != null && $(this).val() != '') {
                   address += $(this).val() + ',';
                }
            });
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                settings.onAddressSelected(address);
            }, 800);
        }
        
        show();
    }

    $.tooltip = {
        settings: null
    };
    $.fn.extend({
        tooltip: function(text) {
            $(this).qtip({
                content: text,
                position: {
                    corner: {
                        target: 'rightMiddle',
                        tooltip: 'leftMiddle'
                    }
                },
                style: {
                    width: 150,
                    name: 'cream', // Inherit the rest of the attributes from the preset dark style
                    tip: 'leftMiddle'
                }
            });
        }
    });

    $.ajaxTooltip = {
        settings: null
    };
    $.fn.extend({
        ajaxTooltip: function(url) {
            $(this).qtip({
                content: {
                    url: url
                },
                position: {
                    corner: {
                        target: 'rightMiddle',
                        tooltip: 'leftMiddle'
                    }
                },
                style: {
                    name: 'blue',
                    tip: {
                        corner: 'leftMiddle',
                        size: {
                            width: 8,
                            height: 5
                        }
                    }
                }
            });
        }
    });


    $.infoTooltip = {
        settings: null
    };
    $.fn.extend({
        infoTooltip: function(text) {
            $(this).qtip({
                content: text,
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomMiddle'
                    }
                },
                show: {
                    delay: 500,
                    effect: { length: 0 }
                },
                style: {
                    name: 'dark', // Inherit the rest of the attributes from the preset dark style
                    fontSize: '7pt',
                    background: '#303030',
                    tip: {
                        corner: 'bottomMiddle',
                        size: {
                            width: 8,
                            height: 5
                        }
                    },
                    padding: 1,
                    border: {
                        width: 0,
                        radius: 3
                    }
                }
            });
        }
    });

    $.wait = {
        settings: null
    };
    $.fn.extend({
        wait: function() {
            $(this).html("<center><img src='/content/images/loader.gif' alt='Loading...' /></center>");
        }
    });
})(jQuery);
