var currentWidth = 0;
var wizardState = "closed";
var locating_me = false;
var settings = null;
var locToggleState="off";
native_page = '';


function $(el) {
	if(typeof el=='object') return el;
	return document.getElementById(el);
}
	
function $type(value) {
	var type = typeof value;
	if(type=='object' && value.constructor.toString().indexOf("Array") != -1) 
		type = 'array';
	else if(value.nodeName)
		type = 'element';
	return type;
}

function $add_event(el, type, callback) {
	el = $(el);
	if(el.addEventListener){
		el.addEventListener(type, callback, false);
	}
	else if (el.attachEvent){
		el.attachEvent('on'+type, callback);
	}
	return true;
}

function $log(thing) {
	console.log(thing);
	if(typeof thing != 'object' && native){
		iphone_call({log: thing});
	}
}

function $create_cookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function $each(ary,func){
	for(var i = 0; i < ary.length; i++){
		func.call(null,ary[i]);
	}
}

function $read_cookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function $erase_cookie(name) {
	$create_cookie(name,"",-1);
}


function set_native_page(page) {
	native_page = page;
}

function update_zip(zip) {
	$('zip').value = zip;
}

function no_back() {
	$('backbtn').style.visibility = 'hidden';
}

function clean_field(el){
	if (el.value == 'Search'){
		el.value = '';
	}
}

function login(username,password) {
	var param = {username:username,password:password,of:'json'};
	new AJAX('/login/do', function(res) {
		res = JSON.decode(res);
		if(res.error){
			if(native){
				iphone_call({loginFail:res.error});
			}
			else{
				alert(res.error);
			}
		}
		else {
			if(native) iphone_call({loginSuccess:1});
			//only used for native right now
		}
	}).post(param);
}

var _load_more_target = null;
function load_more(target, query){
	$('spinner').style.display = 'block';
	$('load_more_text').style.display = 'none';
	var url = '/_includes/more_wines.php';
	var pars = query;
	_load_more_target = target;
	var ajax = new AJAX(url, load_more_callback);
	ajax.update(pars);
}

function load_more_callback(text,status) {
	$(_load_more_target).innerHTML = text;
	$('spinner').style.display = 'none';
	$('load_more_text').style.display = 'inline';
}

function show_stores(){
	document.getElementById('stores').style.display = 'block';
}

function load_side_content(div){
	var topOffset = window.pageYOffset;
	if (topOffset > 53 && wizardState=="closed") { scrollTo(0,1); }
	ca = document.getElementById('wine_details');
	new_div = document.getElementById(div);
	
	if (document.body.getAttribute('class') == 'landscape'){
		new_div.style.left = '480px'
		new_div.style.display = 'block';
		setTimeout("ca.style.left = '-480px'; new_div.style.left = '0px';", 400);
	}
	else {
		new_div.style.left = '320px'
		new_div.style.display = 'block'
		setTimeout("ca.style.left = '-320px'; new_div.style.left = '0px';", 400);
	}
	setTimeout("ca.style.display = 'none';", 500);
}

function load_back_content(div){
	//scrollTo(0,1);
	ca = document.getElementById('wine_details');
	current_div = document.getElementById(div);
	//ca.style.left = '0px';
	if (document.body.getAttribute('class') == 'landscape')
	{
		current_div.style.left = '480px';
		setTimeout("ca.style.left = '0';", 100);
		ca.style.display = 'block';
	}
	else
	{
		current_div.style.left = '320px';
		setTimeout("ca.style.left = '0';", 100);
		ca.style.display = 'block';
	}
	setTimeout("current_div.style.display = 'none';", 400);

}

 

function toggleWizard(){
	
	var myMenu = document.getElementById('searchMenu')
	var mySpacer = document.getElementById('spacer')
	if (wizardState=="closed") {
		myMenu.style.display = "block";
		mySpacer.style.display = "block";
		wizardState="opened";
	} 
	else {
		myMenu.style.display = "none";
		mySpacer.style.display = "none";
		wizardState="closed";
	}
	if(native){
		iphone_call({'wizardState':wizardState});
	}
}

function show_wizard() {
	if(wizardState=='closed') { 
		scrollTo(0,1);
		toggleWizard(); 
	}
	return;
}

function refresh_wizard() {
	if($('useLocationSection')){
		if(setting('lat') && setting('lng')){
			$('useLocationSection').style.display = 'block';
		}
		else {
			$('useLocationSection').style.display = 'none';
		}
	}
	locRefresh();
}



function locToggle() {
	var myToggle = $('loc-toggle');	
	var myToggleBtn = $('loc-toggle-btn');
	var myToggleContent = $('loc-search-content');
	if (locToggleState=="off") {
		myToggle.style.backgroundPosition = "0px -39px";
		myToggleBtn.style.cssFloat = "right";
		myToggleContent.style.display = "block";
		locToggleState="on";
	} 
	else {
		myToggle.style.backgroundPosition = "0px 0px";
		myToggleBtn.style.cssFloat = "left";
		myToggleContent.style.display = "none";
		locToggleState="off";
	}
	locRefresh();
}


function locRefresh() {
	if(locToggleState=='on'){
		if($('ls-usemerch')) $('ls-usemerch').checked = true;
		else if(setting('useZip') && $('zip').value) $('ls-usezip').checked = true;
		else if(setting('lat') && setting('lng')) $('ls-useloc').checked = true;
	}
	else {
		$each(['ls-usemerch','ls-usezip','ls-useloc'], function(el){
			if(!$(el)) return;
			$(el).checked = false;
		});
		if($('zip')) $('zip').value = '';
	}
}

function removeMerchant() {
	$('merchant').value = '0';
	$('wizard_search').submit();
}

function iphone_select_tab(tab_name) {

}

function iphone_switch_view(view_name) {

}

function hide_wizard() {
	if(wizardState=='opened') toggleWizard();
}

function iphone_call(param) {
	if(!native) return;
	if(!param) return;
	var pc = [];
	for(k in param){
		k = encodeURIComponent(k);
		var v = encodeURIComponent(param[k]);
		pc.push("&"+k+'='+v);
	}
	var url = "?preventRequest=1"+pc.join('&');
	window.location = url;
}

function locate_me() {
	if(locating_me) return;
	locating_me = true;
	$('locate-spinner').style.display = 'block';
	iphone_call({'locateMe':1});
}


function done_locating_me() {
	$('locate-spinner').style.display = 'none';
	locating_me = false;
}

function setting(key) {
	return settings[key];
}

function load_settings() {
	var sstr = decodeURIComponent($read_cookie('settings'));
	settings = JSON.decode(sstr);
	if(!settings || $type(settings) != 'object') settings = {};
	if(settings.password) delete(settings.password);
}

function update_setting(key, value, nosave) {
	if(key==null || key=='password') return;
	settings[key] = value;
	if(!nosave) save_settings();

	if($('useLocation') && key=='useLocation'){
		if(value=='1') $('useLocation').checked = true;
		else $('useLocation').checked = false;
	}
}

/** DOESN'T WORK!! **/
function save_settings() {
	var sstr = encodeURIComponent(JSON.encode(settings));
	if(sstr) $create_cookie('settings', sstr, 100);
	$log('save settings: '+sstr);
}

window.onorientationchange=updateOrientation;

function updateOrientation(orientation){
	if(!orientation) orientation = window.orientation;
	switch(orientation){
	
		case 0:
				document.body.setAttribute("class","portrait");
				break;	
				
		case 90:
				document.body.setAttribute("class","landscape");
				break;
		
		case -90:	
				document.body.setAttribute("class","landscape");
				break;
	}

}

/** Window onLoad **/

$add_event(window, 'load', function() {
	
	//init js vars
	load_settings();
	if($('loc-toggle') && $('loc-toggle').className.match('toggleOn')){
		locToggleState = 'on';
	}

	if(price && $('price')) {
		$('price').value = price;	
	}
	if(country && $('country')){
		$('country').value = country;
	}
	if(year && $('year')){
		$('year').value = year;
	}
	
	refresh_wizard();
	
	updateOrientation();

	if($('removeMerchant')){
		$add_event($('removeMerchant'), 'click', function(e) {
			e.preventDefault();
			removeMerchant();		
		});
	}
	
	$add_event($('zip'), 'focus', function() {
		$('ls-usezip').checked = true;
	});
	
});

	
function AJAX (url, callbackFunction) {
	var that=this;			
	this.updating = false;
	this.abort = function() {
		if (that.updating) {
			that.updating=false;
			that._ajax.abort();
			that._ajax=null;
		}
	}
	this.update = function(passData,postMethod) { 
		if (that.updating) return false;
		that._ajax = null;
		if (window.XMLHttpRequest)
			that._ajax=new XMLHttpRequest();							
		else
			that._ajax=new ActiveXObject("Microsoft.XMLHTTP");
		if (that._ajax==null) {
			return false;															 
		} 
		else {
			that._ajax.onreadystatechange = function() {	
				if (that._ajax.readyState==4) {						 
					that.updating=false;								
					that.callback(that._ajax.responseText,that._ajax.status,that._ajax.responseXML);				
					that._ajax=null;																				 
				}																											
			}																												
			that.updating = new Date();															

			if(typeof passData == 'object'){
				var pc = [];
				for(k in passData){
					pc.push(encodeURIComponent(k)+'='+encodeURIComponent(passData[k]));
				}
				passData = pc.join('&');
			}
			
			if (/post/i.test(postMethod)) {
				
				var uri=urlCall+'?'+that.updating.getTime();
				that._ajax.open("POST", uri, true);
				that._ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				that._ajax.setRequestHeader("Content-Length", passData.length);
				that._ajax.send(passData);
			} 
			else {
				var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
				that._ajax.open("GET", uri, true);														 
				that._ajax.send(null);																				 
			}							
			return true;																						 
		}
	}
	this.post = function(data){
		this.update(data,'post');
	};
	this.get = function(data) {
		this.update(data,'get');
	};
	var urlCall = url;				
	this.callback = callbackFunction || function () {};
	
};

var JSON = {

    $specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'},

    $replaceChars: function(chr){
        return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
    },

    encode: function(obj){

        switch ($type(obj)) {
            case 'string':
                return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"';
            case 'array':
				var items = [];
				for(var i = 0; i < obj.length; i++){
					var v = obj[i];
					if(typeof v != 'undefined'){
						items.push(JSON.encode(v));
					}
				}
                return '[' + items.join(',') + ']';
            case 'object':
                var string = [];
				for (key in obj) {
                    var json = JSON.encode(obj[key]);
                    if (json) string.push(JSON.encode(key) + ':' + json);
                }
                return '{' + string + '}';
            case 'number': case 'boolean': return String(obj);
            case false: return 'null';
        }
        return null;
    },

    decode: function(string, secure){
        if ((typeof string != 'string') || !string.length) return null;
        if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
        return eval('(' + string + ')');
    }

};

