/**
 * Extension of the CM.Marker.prototype object to allow a title inside the marker
 * but still be able to use it with CM without customization.
 *
 * Copyright: Peytz & Co - www.peytz.dk
 */
 
/*CM.Util.extend(CM.Marker.prototype, {
    initialize : function (map) {
        this._map = map;
        
        this._image = document.createElement('div');
        this._image.className = 'wml-marker';
        this._image.innerHTML = this._options.title
        this._image.style.position = 'absolute';
        this._image.style.display = 'block'
        
        this._map.getPane(CM.Map.MARKER_PANE).appendChild(this._image);
        
        //Lets overwrite the marker icon, this will make the default redraw work as expected
        var elm = $(this._image);
        this._options.icon.iconSize = new CM.Size(elm.width(), elm.height());
        this._options.icon.iconAnchor = new CM.Point(Math.round(this._options.icon.iconSize.width / 2), Math.round(this._options.icon.iconSize.height));
        
        this._initEvents();
        
        this.redraw(true);
        
        CM.Event.addListener(this._map, 'zoomend', this._forceRedraw, this);
        CM.Event.addListener(this._map, 'tilelayerchanged', this._forceRedraw, this)
    }
});*/

CM.Util.extend(CM.InfoWindow.prototype, {
    _initLayout: function () {
        this._container = document.createElement('div');
        this._container.className = 'wml-info-window-peytz';
        
        this._content = document.createElement('div');
        this._content.className = 'wml-info-window-content';

        this._container.appendChild(this._content);

        this._container.style.visibility = 'hidden';
        this._map.getPane(CM.Map.INFO_WINDOW_PANE).appendChild(this._container);
        CM.DomEvent.stopMousePropagation(this._content)
    },
    _updatePosition: function () {   
        var a = this._map.fromLatLngToDivPixel(this._position);
        
        this._container.style.bottom = (-a.y) + 'px';
        this._container.style.left = (a.x - this._anchor.x) + 'px'
    },
    _updateLayout: function () {
        this._container.style.width = '';
        this._container.style.whiteSpace = 'nowrap';
        
        if (CM.Util.Browser.isIE) {
            this._content.style.zoom = '1'
        }
        
        this._content.style.width = '';
        
        this._container.style.width = $(this._container).find('table').width() + 'px';
        
        this._container.style.whiteSpace = '';
        if (CM.Util.Browser.isIE) {
            this._content.style.zoom = ''
        }
        
        this._anchor = new CM.Point(this._container.clientWidth / 2, $(this._container).outerHeight())
    }
});

CM.Util.extend(CM.LargeMapControl.prototype, {
    zoomLabelConfig : {
        17 : "Bygningar",
        13 : "Grannalag",
        9 : "Øki",
        5 : "Land",
        1 :"Heimurin"
    }
});

  
/* page.js|customers */
// to prevent loadflickering the html is hidden immediately
if (document.getElementById) {
    document.write('<style type="text/css">');
    document.write('#mdBody .mdFormStd,#mdBody .mdFormAvdSelected .mdFormAdv,.mdFormToggle{display:block}');
    document.write('#mdBody .mdFormAdv,#mdBody .mdFormAvdSelected .mdFormStd{display:none}');
    document.write('</style>');
}

// inits script

$(document).ready(function(){
        headDate();
        searchAdvanced();
        map();
        tabs();
        subentries();
        reportLinkLeinki();
});


function subentries(){
    var texts = {
        show : 'Vís undirupptøkur',
        hide : 'Goym undirupptøkur'
    };
    
    $('.vcard').each(function(){
        var elm  = $(this)
        var entries = elm.find('.mdCardSubentries tr');
        var notExpanded = entries.not('.expanded');

        if(notExpanded.length > 0){
            var toggle = $('<p />').addClass('switch-subentries').html(texts.show).appendTo(elm.find('.mdCardData'));
            
            toggle.toggle(function(e){
                toggle.html(texts.hide);
                notExpanded.show();
                e.preventDefault();
            },function(e){
                toggle.html(texts.show)
                notExpanded.hide();
                e.preventDefault();
            });
        }
        
        notExpanded.hide();
    });
}

function headDate(){
    var months=new Array('Januar','Februar','Mars','Apríl','Mai','Juni','Juli','August','September','October','November','Desember');
    var weekday=new Array('Sunnudag','Mánadag','Týsdagur','Mikudagur','Hósdagur','Fríggjadagur','Leygardagur');
    var date = new Date();
    var day = date.getDate();
    var month = date.getMonth();
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;
    $('#mdHeadMenu').append('<p id="mdHeadDate">'+weekday[date.getDay()] + ", " + day + ". " + months[month] + " " + year+'</p>')
}

function reportLinkLeinki(){
    $('#leinki-report #edit-p-description').parent().hide();
    
    $('#leinki-report #edit-p-subject').change(function(e){
        var elm = $('#edit-p-description').parent();
        
        elm.show();
        
        if (this.value == 'dead') elm.hide();
    });
}

function searchAdvanced(){
    $('.mdFormToggle').click(function(){$('.mdFormStd,.mdFormAdv').slideToggle();})
    $('.mdFormToggle').show();
    $('#mdFormNummar').focus();
    $('.mdFormAdv button').click(function(){
        $('.mdFormAdv').find(':text').val('');
        $('.mdFormAdv').find('select option:selected').removeAttr('selected')
        $('.mdFormAdv').find('select option:first-child').attr('selected','selected');
    })
}


function tabs(){
//return;
    $('.mdTabs dt').each(function(i){
        $(this).attr('id','mdTab'+i);
        $(this).not('.selected').next('dd').hide();
        $(this).click(function(){
            if(!$(this).hasClass('selected')){
                $(this).parent('dl').find('dd').hide().end().find('dt.selected').removeClass('selected');
                $(this).addClass('selected').next('dd').show();
                
                if (i == 0) {
                    window.location.hash = '#mdCards';
                } else {
                    window.location.hash = '#mdMap';
                }
            }
        })
    })
}

/* map.js|customers */
function map(){
   var mdMap = $('#mdMap');
    var iconImages = {
        person   :'/img/nummar/map/marker_person.png',
        company  :'/img/nummar/map/marker_company.png',
        promoted :'/img/nummar/map/marker_promoted.png'
    };
    
    if (mdMap.get(0)) {
        var map = new CM.Map(mdMap.get(0), new CM.Tiles.CloudMade.Web({
            key : '83068f6147114ac1be248e1875489f97',
            styleId : 9659
        }));
        
        //Always availible
        mdMap.data('map', map);
        mdMap.data('markers', []);
        
        map.addControl(new CM.LargeMapControl());
        
        //get the search criteria and send it through the proxy
        var input = $('#mdFormNummarQueryString');
        
        //fix up events for the onclick of the two tabs.
        $('.mdTabs dt:eq(0)').click(function (e) {
            detach();
            e.preventDefault();
        }).next().next().click(function (e) {
            attach();
            e.preventDefault();
        })
        
        function detach() {
            window.location.hash = '#mdCards';
        }
        
        function attach() {
            detach();
            window.location.hash = '#mdMap';
        }
        
        function infoWindow(marker) {
            try {
                content = [
                    '<table class="' + marker._options.classes.join(' ') + '" cellpadding="0" cellspacing="0">',
                    '<tr><td class="topLeft"></td><td class="topMiddle"></td><td class="topRight"></td></tr>',
                    '<tr><td class="middleLeft" width="12"><div class="wrap">x</div></td><td class="content">',
                    '<h2 class="fn n">' + marker._options.json.firstName + ' ' + marker._options.json.lastName + '</h2>',
                    '<address class="adr">',
                    '<span class="street-address">' +  marker._options.json.ftAddress.streetName + ' ' + marker._options.json.ftAddress.streetNumber + '</span><span class="postal-code">' + marker._options.json.ftAddress.zip + '</span> <span class="locality">' + marker._options.json.city + '</span></address>',
                    '<p class="tel">' + marker._options.json.phoneNumbers[0].phoneNumber + '</p>',
                    '</td><td class="middleRight" width="12"><div class="wrap">x</div></td></tr>',
                    '<tr><td class="bottomLeft"></td><td class="bottomMiddle"></td><td class="bottomRight"></td></tr></table>'
                ];
                
                marker.openInfoWindow(content.join(''), {
                    uid : marker._options.uid
                });
                
                marker.hide();
            } catch (error) {}}
        
        if (window.location.hash == '#mdMap') {
            $('.mdTabs dt:eq(0)').removeClass('selected').next().hide().next().addClass('selected').next().show();
            attach();
        }
        
        //61.965124,-6.778564
        map.setCenter(new CM.LatLng('61.965124', '-6.778564'), 8);
        
        if (input.get(0)) {            
            var icon  = new CM.Icon();
            icon.iconSize = new CM.Size(43, 68);
            icon.iconAnchor = new CM.Point(21.5, 62);
            
            var markers = mdMap.data('markers');
            
            var service = 'contacts_grp.get_ctx_adv';
            if (input.attr('title').match(/p_comq/)) {
                var service = 'contacts_grp.get_ctx_com'
            }
                     //console.log(json_body.contacts);
            //this will recieve a collection so thats why we have to each them.
            //$.getJSON('http://www.nummar.fo/@api/' + service + '?' + input.attr('title').replace('p_limit=10', 'p_limit=250'), function (response) {
                     //$.each(response.contacts, function (i, contact) {
               $.each(json_body.contacts, function (i, contact) {
                
                    try {
                        var coord = contact.ftAddress.coord;
                        var classes = [
                            'pcoMarker'
                        ];
                        
                        icon.image = iconImages.person;
                        if (contact.contactType == 'ORGANIZATION') {
                            icon.image = iconImages.company;
                            classes.push('pcoMarkerY');
                            
                            if (contact.premium) {classes.push('pcoMarkerPromoted');}
                        }
                        

                        if (coord.y != null && coord.x != null) {
                            var marker = new CM.Marker(new CM.LatLng(coord.y, coord.x), {
                                title : contact.firstName + ' ' + contact.lastName,
                                uid : contact.id,
                                icon : icon,
                                classes : classes,
                                json : contact
                            });
                            
                            markers[contact.id] = marker;
                            
                            map.addOverlay(marker);
                            
                            var mdCardDataTelElm = $('#uid' + contact.id).parent().parent().find('.mdCardData > .tel:last');
                            if (mdCardDataTelElm) {
                                $('<p class="locate">Vís á korti</p>').insertAfter(mdCardDataTelElm).click(function(e){
                                    var marker = markers[$(this).parents('.vcard').find('.uid').text()];
                                    $('#mdTab0').removeClass('selected').next().hide().next().addClass('selected').next().show();
                                    map.setCenter(marker.getLatLng(), 16);
                                    infoWindow(marker)
                                    
                                    attach();
                                    
                                    for (i in markers) {markers[i].hide();}
                                });
                            }
                            
                            CM.Event.addListener(marker, 'click', function () {
                                try {markers[map._infoWindow._options.uid].show();} catch (error) {}
                                
                                infoWindow(this);
                            })
                            
                        }
                    } catch (error) {}});
                
                //map.zoomToBounds(new CM.LatLngBounds(
                    //new CM.LatLng(bounds.minLat, bounds.minLng),
                    //new CM.LatLng(bounds.maxLat, bounds.maxLng)
                //))
            //});
            
            CM.Event.addListener(map, 'infowindowclose', function (e) {markers[this._infoWindow._options.uid].show();});
        }
    }
}




