var _location;
var loki;
var active_channel;


var all_variables  = ['longitude', 'latitude', 'house_number', 'street', 'city', 'region', 'region_code', 'postal_code', 'country', 'country_code'];
    


function toolbarSuccess(location) {
    _location = location;
    if (active_channel) {
        submitChannel(active_channel);
        active_channel = false;
    }
}

function toolbarFailure(error) {
    if (error == 1) alert('Loki cannot find the scanning service. We recommend that you uninstall and re-install Loki.');
    else if (error == 2) alert('We cannot detect your wireless adapater. Check to make sure its on and then reload the page.');
    else if (error == 3) alert('Loki cannot see any Wi-Fi access points in range and therefore cannot determine your location.');
    else if (error == 4) alert('An unauthorized request was performed.');
    else if (error == 5) alert('Server unavailable.');
    else if (error == 6) alert('Loki cannot determine your location. You are most likely outside of our coverage area.');
    else if (error == 7) alert('You are using an unauthorized proxy. Contact your network administrator.');
//    jQuery('.launch-button').hide();
}


function replaceVariables(source) {
    var result = '' + source;
    var value = '';
    for (var i=0;i<all_variables.length;i++) {
        if (all_variables[i] in _location) {
            value = _location[all_variables[i]];
        }else {
            value = '';
        }
        result = result.replace('#' + all_variables[i] + '#', value);
    }
    return result;
}

function submitChannel(channel_id){
    var channel = channels[channel_id];
    var form = document.createElement('form');
    var url = replaceVariables(channel['url']);
    if (url.indexOf('zillow') == -1)
        url = url.toLowerCase();
    form.action = url;
    form.id = 'dialog-form';
    form.method = channel.method;
    form.target = '_blank';
    var user_query = false;
    for (var i=0;i<channel.params.length;i++) {
        if (channel.params[i].value) {
        	var value = replaceVariables(channel.params[i].value);
		    if (url.indexOf('hotornot')||url.indexOf('zipcar')) 
		    	value = value.toLowerCase();
            jQuery(form).append('<input type="hidden" name="' + channel.params[i].name + '" value="' + value + '" />');
        }
    }
    form.style.display = 'none';
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}
	
jQuery(document).ready(
function () {
        jQuery('.launch-button').click(
        function() {
            if (!jQuery(this).attr('channel_id')) {
                return false;
            }
            if (!channels||!(jQuery(this).attr('channel_id') in channels)) {
                return false;
            }
            if (!_location) {
                active_channel = jQuery(this).attr('channel_id');
                loki.onSuccess = toolbarSuccess;
                loki.onFailure = toolbarFailure;
                loki.setKey('loki.com');
                loki.requestLocation(true,loki.FULL_STREET_ADDRESS_LOOKUP);
            }else{
                submitChannel(jQuery(this).attr('channel_id'));
            }
        }
        );
        
    jQuery('.channel-button').click(
    function() {
        if (!jQuery(this).attr('channel_id')) {
            return false;
        }
        var button = this;
        if (!jQuery(this).attr('installed')) {
            jQuery.get('/gallery/install?id='+jQuery(this).attr('channel_id'), {}, function(responce) {
                responce = eval('(' + responce + ')');
                jQuery(button).attr('installed', true);
                jQuery(button).html('Remove FindMe page');
                jQuery('.dcounter[channel_id=' + jQuery(button).attr('channel_id') + ']').html(responce.downloads);
            });
        } else {
            jQuery.get('/gallery/uninstall?id='+jQuery(this).attr('channel_id'), {}, function(responce) {
                jQuery(button).attr('installed', '');
                jQuery(button).html('Add to FindMe page');
            });

        }

    }
    );  
    setTimeout(function(){
           loki = new LokiAPI();
           if (!loki||!('setKey' in loki)) 
                jQuery('.launch-button').hide();
    }, 0);

}
);


function addChannel(id) {
    jQuery.post( '/gallery/install?id='+id, {}, function() {
        jQuery('#loki-dowload-count-'+id).load('/gallery/channels/'+id+'/count');
    });
}
