//emulate popup function...
var popWindow = function(u,w,h,popEl){
	if(!popEl){
		e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
		if(e == 'png' || e == 'gif' || e == 'jpg')
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><img src=\""+ u +"\" width=\"" + w + "\" height=\"" + h + "\" border=\"0\" /></div>",{overlay:20});
		else
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><iframe src=\""+ u +"\"  width=\"" + w + "\" height=\"" + h + "\" border=\"0\" frameborder=\"0\"></iframe></div>",{overlay:20});
	}
	popEl.modal({
			onOpen: function (dialog) {
						dialog.data.addClass('alert');
						dialog.container.css('height','auto');
						dialog.overlay.fadeIn('normal', function () {
							dialog.container.show('normal', function () {
								dialog.data.slideDown('normal'); // See Other Notes below regarding
														   // data display property and
														   // iframe details
							});
						});
					},
			onClose: function (dialog) {
						dialog.data.slideUp('normal', function () {
						  dialog.container.hide('normal', function () {
							dialog.overlay.fadeOut('normal', function () {
							  $.modal.close(); // must call this to have SimpleModal
											   // re-insert the data correctly and
											   // clean up the dialog elements
							});
						  });
						});
					}
	});
	$("#modalContainer").css('width',w).css('margin-left',(w / 2) * -1).css('height',h).css('margin-top',(h / 2) * -1); 
}

//make uniqID
var uid = (
	function(){
		var id=0;
		return function(){
			return id++ ;
		};
	}
)();


geocoder = new GClientGeocoder();

var getLocation = function(addr){
	geocoder.getLocations(addr,function(response){
		if(!response || response.Status.code != 200){
			alert("Sorry, we were unable to locate your address.");
		}else{
			var my_location = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			var glatlng1 = new GLatLng(my_location.lat, my_location.lon);
		}
		return glatlng1;
	});
}

//make same height
var make_same_height = function(selector){
	var max_height = 0;
	$(selector).each(function(){
		if($(this).height() > max_height){
			max_height = $(this).height();
		}
	});
	$(selector).height(max_height);	
}




$(document).ready(function(){

	//hide blank br before modules
	$(".module_contents").each(function(){
		if($(this).prev('br').length == 1){
			$(this).prev('br').remove();
		}
	});
	//kill empty titles and articles
	$(".article,.title,.content").each(function(){
		if(!$.trim($(this).text()) && !$(this).find('img,object,embed,form,input,frame,.sIFR-replaced').length){
			$(this).remove();
		}
	});


	$(".store_module div.listing div.no_thumb span").each(function(){
		$(this).css({marginTop:72.5 - ($(this).outerHeight() / 2),display:'block'});
	});
	
	//build price_lines for logged users
	$(".store_module.logged div.article").each(function(){
		var cA = $(this);
		//build select menu
		var opts = $('<select name="selector"><option value="">-- selecteer --</option></select>').change(function(){
			i = $(this).val();
			if(i){
				$(this).next().html($(this).parents('div.article:eq(0)').find(".prices .price_line:eq(" + i + ") div.ui").html());
				$(this).parent().next().html($(this).parents('div.article:eq(0)').find(".prices .price_line:eq(" + i + ") div.price span.price").html());
				$(this).next().find('input').removeAttr('disabled');
			}
			//order button
			$(this).parents('div.article:eq(0)').find(".price_selector .submit").mousedown(function(){
				o = $(this).parents('.price_selector').find('.input');
				if(!o.val())
					o.val(1);
			});
		});
		var p;
		$(this).find(".prices .price_line").each(function(){
			p = $(this).find('span.new_price').html();
			r = $(this).children('div.price').find('span.ref').text();
			t = $(this).children('div.price').find('span.article').text();
			opts.append($('<option value="' + cA.find(".prices .price_line").index($(this)) + '">' + t + ' (' + r + ')</option>'));
		});
		$(this).find(".prices .price_line input").attr('disabled','disabled');
		$(this).find(".prices").prepend($('<div class="price_selector"><span class="selector_ui"></span></div><div class="price"></div>')).find('.price_selector').prepend(opts);
	});





	//change all popups...
	var img = new Array();
	$(".article a").each(function(){
		i = 0;

		//change all onclick popups
		if($(this).attr('onclick')){
			i = $(this).attr('onclick').toString().indexOf("dow.open(this.href,");

			if(i){
				w = 640;
				h = 480;
				
				u = $(this).attr('href');//.replace(/(\/db\/.*\/)(.*)$/,'$1popup.$2');
				e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
				
				if(e == 'png' || e == 'gif' || e == 'jpg'){
					var id = 'popwinlink_' + uid();
					$(this).attr('id',id);

					img[id] = new Image();
					img[id].onload = function(){
						img[id].onload = null;
						w = img[id].width;
						h = img[id].height;
	
						$("a#" + id).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");
					}
					img[id].src = u;
				}else{
					c = $(this).attr('onclick').toString();

					h = parseInt(c.match(/height=([0-9]+)/)[1]) + 25;
					w = parseInt(c.match(/width=([0-9]+)/)[1]) + 25;
	
					$(this).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");				
				}
			}

		//change all movie files
		}else if($(this).attr('href') && $(this).attr('href').match(/.(flv|FLV)$/)){
			//get filename...
			u = $(this).attr('href').match(/(\/db\/.*.(flv|FLV)$)/)[1];
			$(this).addClass('popWindowLink').attr('href',"javascript:popWindow('/domains/huijgsport.nl/video.php?file=" + u + "',320,260);");		
		}
	});








	//remove search on google multi maps module
	if($(".googlemultimaps_module").length){
		$('#left').find('.search_module').parents('div.article:eq(0)').hide();
		$('#left').find('.submenu_module').parents('div.article:eq(0)').hide();		
	}

	//change layout
	if(!$("#middle.right_middle").length){
		$("#left").css('display','none');
	}
	
	//change menu's
	$("#menu > ul > li:first,#left .leftmenu > ul > li:first,#topmenu > ul > li:first,#bottommenu > ul > li:first").addClass('first');

	//open left menu
	var last_menu_zIndex = 10;
	$("#left .leftmenu ul li,#menu ul li").hover(
		 function(){
			$(this).addClass('hover');
			if($(this).children('ul:eq(0)').is(':hidden') && $(this).parents('ul').length < 2){
				last_menu_zIndex++;
				$(this).children('ul:eq(0)').css('z-index',last_menu_zIndex).slideDown('fast');
			}
		 },
		 function(){
			$(this).removeClass('hover');
			if($(this).children('ul:eq(0)').is(':visible') && !$(this).hasClass('hold')){
				$(this).children('ul:eq(0)').slideUp('fast');
			}
		 }
	);
	$("#left .leftmenu").parents('.article').addClass('gray');

	//open current submenu onload
	if($("#left .leftmenu a.current_buttonID").length){
		$("#left .leftmenu a.current_buttonID").parents('li:last').addClass('hold').trigger('mouseover');
	}
	
	$('.dealer_module .search form').submit(function(e){
		e.preventDefault();
		
		$(this).parents('.search').addClass('loading');
		
		popWindow('',300,50,$('<div id="loading_status">Contact maken met Google Maps...</div>'));
		
		var location = $(this).find('input[name=postcode]').val() + ', the Netherlands';
		geocoder = new GClientGeocoder();
		geocoder.getLocations(location, getLoc);
		return false;
	});
});

var glatlng1;
function getLoc(response){
	if(!response || response.Status.code != 200){
		alert("Sorry, we were unable to locate your address.");
	}else{
		var my_location = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
		glatlng1 = new GLatLng(my_location.lat, my_location.lon);

		//get all from database
		$.getJSON('/domains/carnivoer.nl/modules/dealers/agent.php', handleData);
	}
}

function loadAddrContent(getID){
	$('#container div.dealer_module div.listing').load('/verkooppunten #container div.dealer_module div.listing',{'found':array2json(getID)},function(){
		$('.dealer_module .search').removeClass('loading');
		$.modal.close();
	});
}

var getID = new Array();
var getAddressID = new Array();
var getCompanyID = new Array();
var addressData;
function handleData(data){
	if(!data){
		alert("Sorry, no addresses from the database?");
	}else{
		var i = 0;
		for(k in data['data']){
			getAddressID[i] = k;
			getCompanyID[i] = data['companies'][k];			
			i++;
		};
		addressData = data['data'];
		connect2google(0);
	}
}

var k;
var waitTmr;
function connect2google(k){
	if(addressData[getAddressID[k]]){
		geocoder = new GClientGeocoder();
		geocoder.getLocations(addressData[getAddressID[k]],
			function(response){
				kmdistance = 0;
				if(response.Status.code == 200){
					
					$('#loading_status').html('Vraag afstand naar:<br />' + getCompanyID[k]);
					
					var new_location = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					var glatlng2 = new GLatLng(new_location.lat, new_location.lon);
					var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
					var kmdistance = (miledistance * 1.609344).toFixed(1);
					
					//console.debug('Found distance: ' + kmdistance + ' found key: ' + getAddressID[k]);
				}
				if(response.Status.code == 200 && kmdistance){
					getID[getID.length] = [parseFloat(kmdistance),parseInt(getAddressID[k])];
					connect2google(k + 1);
				}else{
					//wait and do this 
					//console.debug('No distance ' + kmdistance +', got status response: ' + response.Status.code);
					waitTmr = setTimeout('connect2google(' + k + ');',500);
				}
			}						
		);
	}else{
		loadAddrContent(getID);
	}
}

/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 * 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}

