/*
 * RBFF map buttons control
 */
function RBFFButtonControl() {}
RBFFButtonControl.prototype = new GControl();
RBFFButtonControl.prototype._container = null;
RBFFButtonControl.prototype.initialize = function(map) {
    var _messenger       = window;
    var _templates       = {};
    var _parser          = TrimPath.parseDOMTemplate;

    _templates['gm_button_control'] = _parser('gm_button_control_tpl');
    
    var html   = _templates['gm_button_control'].process({
        profile_name : settings['profile_display_name'],
        base_url     : settings['base_url'],
        embedded     : settings['embedded'] || false
    });
    _container = $(html)[0];

    map.getContainer().appendChild(_container);


    /* Controller */
    $('#show_labels:input', _container).livequery('click', function() {
        var v = false;

        if ($(this).attr('checked')) {
            v = true;
        }

        $(_messenger).trigger('mp::labels::toggle::changed', [v]);

        /* Don't return false: what can I say... IE */
        //return false;
    });
       
    $('#show_navaid_markers:input', _container).livequery('click', function() {
        var v = false;
    
        if ($(this).attr('checked')) {
            v = true;
        }
    
        $(_messenger).trigger('mp::gwmarkers::toggle::changed', [v]);
    
        /* Don't return false: what can I say... IE */
        //return false;
    });
    
    $('#noaa_charts_list', _container).livequery('change', function() {
        var v = false;
    
        if ($(this).val() != -1) {
            v = true;
        }
    
        $(_messenger).trigger('mp::gwcharts::toggle::changed', [v]);
    
        /* Don't return false: what can I say... IE */
        //return false;
    });
       
    $('#show_noaa_charts:input', _container).livequery('click', function() {
        var v = false;
    
        if ($(this).attr('checked')) {
            v = true;
        }
    
        $(_messenger).trigger('mp::gwcharts::toggle::changed', [v]);
    
        /* Don't return false: what can I say... IE */
        //return false;
    });
       
    $('*[@rel=show_share]', _container).livequery('click', function() {
        $(_messenger).trigger('all::open::clicked', ['share']);
            
        return false;
    });
    $('div[@rel=show_help]', _container).livequery('click', function() {
        $(_messenger).trigger('all::open::clicked', ['help']);
            
        return false;
    });
	
	$("#show_navaid_markers:input", _container).attr("checked",false); 
    $("#show_noaa_charts:input", _container).attr("checked",false);
    
    return _container;
}
RBFFButtonControl.prototype.toggleLabels = function(show) {
    $('#show_labels:input', this._container).attr('checked', true);
    
    if (!show) {
        $('#show_labels:input', this._container).attr('checked', false);
    }
}
RBFFButtonControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}
RBFFButtonControl.prototype.toggleGWControls = function(show) {
    if (!show) {
        $('.map_control_items_geowake', this._container).hide();
    }else{
        $('.map_control_items_geowake', this._container).show();  
    }
}

/*
 * Share screen control
 */
function RBFFShareControl() {}
RBFFShareControl.prototype = new GControl(true,true);
RBFFShareControl.prototype._container = null;
RBFFShareControl.prototype.emailRe    = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
RBFFShareControl.prototype.initialize = function(map) {
    var self       = this;
    var _messenger = window;
    var _templates = {};
    var _parser    = TrimPath.parseDOMTemplate;
    var qs         = controller.getPermLink();
    var link_url   = window.location.href.replace(window.location.search, '') + qs;
    var message    = 'Hi, I\'d like to share a map link from TakeMeFishing.org with you.\n\nLink: ' + link_url + '\n\nA day on the water is a great way to learn new skills, have fun & connect with the people who matter most.';
    var embed_code = '<iframe frameborder="0" src="' +
                     settings['base_url'] + 'share/places/state/' + settings['curr_state'] + qs + 
                     '" target="_blank" align="left" height="700" width="900" scrolling="no" bgcolor="#C9D3DE">' +
                     '</iframe>';
    
    _templates['gm_share_control'] = _parser('gm_share_control_tpl');

    var html = _templates['gm_share_control'].process({
        base_url: settings['base_url'],
        link_url: this.htmlspecialchars(link_url),
        embed_code: this.htmlspecialchars(embed_code)
    });
    
    var $html               = $(html);
    var $email_msg_wrapper  = $html.find('#share_email_message_wrapper');
    var email_txtarea       = '<textarea id="share_email_message" name="message">' + message + '</textarea>';
    
    $email_msg_wrapper.html(email_txtarea);
    
    _container = $html[0];

    map.getContainer().appendChild(_container);

    /* Controller */
    $('a[@rel=close]', _container).livequery('click', function() {
        $(_messenger).trigger('all::close::clicked', []);

        return false;
    });
    /* Select url on focus*/
    $('input#link_url', _container).focus(function() {
        this.select();
        return true;
    });
    $('form', _container).livequery('submit', function() {
        var $form    = $(this);
        var $inputs  = $form.find('input[@type=text]');
        
        var errors = [];
        
        var to_email = $inputs.filter('[@name=to_email]').val();
        if (to_email == '') {
            errors.push('"To" is mandatory');
        }
        else if (!self.isEmailValid(to_email)) {
            errors.push('"To" is not a valid email address');
        }
        
        var from_email = $inputs.filter('[@name=from_email]').val();
        if (from_email == '') {
            errors.push('"From" is mandatory');
        }
        else if (!self.isEmailValid(from_email)) {
            errors.push('"From" is not a valid email address');
        }
        
        var message = $('#share_email_message').val();
        if (!message) {
            errors.push('"Message" is mandatory');
        }
        
        if (errors.length > 0) {
            alert(errors.join('\n'));
            return false;
        }
        
        $form.data('current', true);
        
        var $buttons = $form.find('input[@type=submit]');
        $buttons.attr('disabled', true);
        
        var values = $form.serializeArray();
        var action = $form.attr('action');
        $.post(action, values, function(result, status) {
            var is_current = $form.data('current') == true;
                
            var response = {success:false};
            try {
                response = eval( '(' + result + ')' );
    
                if (!(success in response)) {
                    response.success = false;
                }
            } catch(e) {}
            
            // feedback
            if (response.success == true) {
                alert('Email successfully sent.');
            }
            else {
                alert('Sending email failed. Please try again later.');
            }
            
            if (!is_current) {
                return;
            }
            
            // reset UI
            $buttons.attr('disabled', false);
            
            if (response.success == true) {
                $inputs.each(function(i,e) {
                    e.value = e.defaultValue;
                });
                //$form.find('textarea').each(function(i,e) {
                //    e.value = '';
                //});
            }
        });

        return false;
    });
    $('li.tab a', _container).livequery('click', function() {
        var $this   = $(this);
        var $tab    = $this.parents('.tab:first');
        var rel     = $tab.attr('rel');
        var relSel  = '[@rel=' + rel + ']';
        var $panels = $tab.parents('.tabs:first').next().find('.panel');
        
        $panels.hide().filter(relSel).show();

        return false;
    });

    return _container;
}
RBFFShareControl.prototype.isEmailValid = function(email) {
    return this.emailRe.test(email);
}
RBFFShareControl.prototype.htmlspecialchars = function(string, quote_style, charset, double_encode) {
    // Convert special characters to HTML entities  
    // 
    // version: 912.1315
    // discuss at: http://phpjs.org/functions/htmlspecialchars
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');
 
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }
 
    return string;
}

/*
 * Help screen control
 */
function RBFFHelpControl() {}
RBFFHelpControl.prototype = new GControl();
RBFFHelpControl.prototype._container = null;
RBFFHelpControl.prototype.initialize = function(map) {
    var _messenger        = window;
    var _templates        = {};
    var _parser           = TrimPath.parseDOMTemplate;

    var show_hide_checked = false;
	if(readCookie('rbff_show_hide')) {
	    show_hide_checked = true;
	}

    _templates['gm_help_control'] = _parser('gm_help_control_tpl');

    var html   = _templates['gm_help_control'].process({
        show_hide_checked: show_hide_checked
    });
    _container = $(html)[0];

    map.getContainer().appendChild(_container);

    /* Controller */
    $('a[@rel=get_started]', _container).livequery('click', function() {
        $(_messenger).trigger('all::close::clicked', []);

        return false;
    });

	$('#showhide', _container).livequery('click', function() {
		var hide = false;
		
        if ($(this).attr('checked')){
            hide = true;
        }

    	if(hide) {
    		createCookie('rbff_show_hide', false, 3);
    		$('#showhide').attr('checked', true);
    	}
    	else {
    		eraseCookie('rbff_show_hide');
    		$('#showhide').removeAttr('checked'); 		
    	}
	});

    return _container;
}
RBFFHelpControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}

/*
 * Hotspot screen control
 */
function RBFFHotspotControl(options) {
    _view = 'start';

    var view = (options || {}).view;
    
    if (view == 'finish' || view == 'match') {
        _view    = view;
        _options = options;
    }
}
RBFFHotspotControl.prototype = new GControl();
RBFFHotspotControl.prototype._container = null;
RBFFHotspotControl.prototype._view      = null;
RBFFHotspotControl.prototype._options   = null;
RBFFHotspotControl.prototype.initialize = function(map) {
    var _messenger        = window;
    var _templates        = {};
    var _parser           = TrimPath.parseDOMTemplate;

    _templates['gm_hotspot_control_box']    = _parser('gm_hotspot_control_box_tpl');
    _templates['gm_hotspot_control_start']  = _parser('gm_hotspot_control_start_tpl');
    _templates['gm_hotspot_control_match']  = _parser('gm_hotspot_control_match_tpl');
    _templates['gm_hotspot_control_finish'] = _parser('gm_hotspot_control_finish_tpl');
    _templates['gm_hotspot_control_error']  = _parser('gm_hotspot_control_error_tpl');

    /* Generate control content */
    var content = '';
    if (_view == 'start') {
        // if map zoom is too far out, prevent new spot
        if(map.getZoom() < 14) {
             $(_messenger).trigger('all::hotspot::zoom::change', [14]);
        }
        
        content = _templates['gm_hotspot_control_start'].process({
            base_url: settings['base_url']
        });
    }
    else if (_view == 'match') {
        content = _templates['gm_hotspot_control_match'].process({
            base_url : settings['base_url'],
            matches  : _options.hotspot.matches
        });
    }
    else if (_view == 'finish') {
        content = _templates['gm_hotspot_control_finish'].process(_options.hotspot);
    }

    /* Generate control wrapper and insert content */
    var html = _templates['gm_hotspot_control_box'].process({
        content: content
    });
    
    var $html = $(html);
    
    if (_view == 'match' && _options && _options.hotspot) {
        $html.find('a').filter('.force_save').data('hotspot', _options.hotspot);
    }
    
    _container = $html[0];
    map.getContainer().appendChild(_container);

    /* Controller */
    $('a[@rel=cancel]', _container).livequery('click', function() {
        $(_messenger).trigger('all::close::clicked', []);

        return false;
    });

    $('a[@rel=drop]', _container).livequery('click', function() {
        $(_messenger).trigger('all::close::clicked', []);

        return false;
    });
    $('a[@rel=continue]', _container).livequery('click', function() {
        $('form', _container).submit();

        return false;
    });
    
	$('a.force_save', _container).livequery('click', function() {
        var $this   = $(this);
        var hotspot = $this.data('hotspot');
        
        if (!hotspot) { return false; }
        
		$(_messenger).trigger('all::open::clicked', ['hotspot', {view: 'finish', hotspot:hotspot}]);

		return false;
	});

	$('a.begin_add_hotspot', _container).livequery('click', function() {
		var type = $(this).attr('rel');

        if ($('#terms_agree:checked').length != 1) {
            alert('You have to agree to the terms and conditions.');

            return false;
        }

		if (type != 'facility' && type != 'water' && type != 'hotspot') {
		    return false;
		}
		
		$(_messenger).trigger('all::hotspot::add::clicked', [type]);
		$(_messenger).trigger('all::close::clicked', []);

		return false;
	});
    
    return _container;
}
RBFFHotspotControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}

/*
 * Nautical Button Control
 */
function RBFFNauticalControl() {}
RBFFNauticalControl.prototype = new GControl();
RBFFNauticalControl.prototype._container = null;
RBFFNauticalControl.prototype.initialize = function(map) {
    var _messenger        = window;
    var _templates        = {};
    var _parser           = TrimPath.parseDOMTemplate;

    _templates['gm_nautical_control'] = _parser('gm_nautical_control_tpl');

    var html   = _templates['gm_nautical_control'].process();
    _container = $(html)[0];

    map.getContainer().appendChild(_container);
    
    /** Controller **/
    $('a[@rel=nautical_info]', _container).livequery('click', function() {
        $(_messenger).trigger('mp::nautical::toggle::changed', []);

        return false;
    });
    
    return _container;
}
RBFFNauticalControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
}


