var d = false;

$(document).ready(function(){

	// temporal way of loading all the products.
	$('#load_all').click(function(){
		var url = location.href.split("#");
		location.href=url[0] + '#all';
		filter();
		return false;
	});

	// set "is it a search" variable
	if(document.URL.indexOf("?search=set") >= 0){ 
		var searchset = "";
	}else {
		var searchset = "?search=set";
	}

	$('#search').click(function(){
		var values = get_form_values();

		location.href = values['url'] +
				searchset +
				"#size:" + values['size'] +
				"+space:" + values['space'] +
				"+heated:" + values['heated'] +
				"+standard:" + values['standard'];
		filter();
		return false;
	});

	// Checking if vars have been passed on the URL
	var url = location.href.split("#");
	if (url[1]) {
		put_url_values();
		filter();
	}

	//$.cookies.del('exp_likes');
	// I Like this door button!
	show_likes();
	$('#like_this').click(function(){
		// retrieving json data
		var likes = $.cookies.get('exp_likes');
		if (d) console.log(likes);

		if (!likes) {
			likes = [];
		}
		var door = {
			name : $('input[name=title]').val(),
			style : $('input[name=style]:checked').val(),
			color : $('input[name=color]:checked').val(),
			window : $('input[name=window]:checked').val()
		};
		likes.push(door);
		$.cookies.set('exp_likes', JSON.stringify(likes), {path: '/', expires: 7});
		if (d) console.log(JSON.stringify(likes));
		show_likes();
		return false;
	});

	$('#clear_all').click(function(){
		$.cookies.del('exp_likes');
		$('.doors_liked .list').html('');
		return false;
	});

	$('#request_info').click(function(e){
		//alert("Unicorns will make this work eventually.");
		
		//Check to see if anything has been selected.
        if ($.cookies.get('exp_likes')) {
            return true;
        }
        //Otherwise give people an option
        var ok = confirm('You have not selected any products. Are you sure you would like to continue?');
        if (ok) {                
            return true;
        }
        else {
            //Prevent the event and remain on the screen
            e.preventDefault();
            return false;
        }
		
	});

	$('.questionmark').hover(function(){
		$(this).siblings('.help').show();
	}, function(){
		$(this).siblings('.help').fadeOut();
	});

    
    //Makes the product show room help boxes stay persistant while moused over
    $('.help').mouseover(function() {
        if($(this).is(':animated')) {
            $(this).stop().animate({opacity:'100'});
        }
        $(this).show();
    }).mouseout(function(){
        $(this).fadeOut();
    });
    
    //Add the request a quote hooks
    hook_request_manager();
});

var get_form_values = function() {

	var vals = {
		url : location.href.split("#")[0],
		size : $('#size').val() ? $('#size').val()  : '',
		space : $('input:radio[name=space]:checked').val() ? $('input:radio[name=space]:checked').val() : '',
		white : $('input[name=white]').attr('checked') ? $('input[name=white]').attr('checked')  : '',
		heated : $('#heating').val() ? $('#heating').val()  : '',
		standard : $('#standard').val() ? $('#standard').val()  : ''
	}
	return vals;
};

/**
 * Gets the values from the URL and puts them into the form
 */
var put_url_values = function() {
	var vars = [];
	var url_vals = location.href.split("#")[1];
	var hash = url_vals.split("+");

	for(var i = 0; i < hash.length; i++) {
		h = hash[i].split(':');
        vars.push(h[0]);
        vars[h[0]] = h[1];
		switch(h[0]) {
			case 'size':
				$('#size').val(h[1]);
			break;
			case 'space':
				$('input[name=space]').filter('[value='+h[1]+']').attr('checked', true);
				break;
			case 'white':
				if (h[1] == "yes")
					$('input[name=white]').attr('checked', true);
				break;
		}
	}


	var vals = {
		url : location.href.split("#")[0],
		//size : $('#size').val() ? $('#size').val()  : '',
		//space : $('input:radio[name=space]:checked').val() ? $('input:radio[name=space]:checked').val() : '',
		//white : $('input[name=white]').val() ? $('input[name=white]').val()  : '',
		heated : $('#heating').val() ? $('#heating').val()  : '',
		standard : $('#standard').val() ? $('#standard').val()  : ''
	}
};

/**
 * Takes all the variables from the url and requests the results via POST
 */

var filter = function(){
	var area = $('#showroom_list .content');
	var html = '';
	$('.overlay').show();

	var hash = location.href.split("#");
	if (d) console.log(hash[0]);
	hash = hash[1].split("+");
	var map = new Array();

	for(var i = 0; i < hash.length; i++) {
		h = hash[i].split(':');
        //map.push(h[0]);
        map[i] = h[1];
		if (d) console.log(map[i]);
	}
	if (d) console.log(map);
	$.post('/index.php/ajax/', {
			//size: map[0],
			//space: map[1],
			//white: map[2],
			heated: map[2],
			standard: map[3]
		}, function(html){
			area.html(html).fadeIn('slow', function(){
				$('.overlay').hide();
			});
		}
	);




};

/**
 * Shows the list of doors added to the "cart" thing.
 * (I keep calling this a cart, but it's not. I don't even know what this is)
 */
var show_likes = function(){
	// rendering previously liked doors
	var likes = JSON.parse(JSON.stringify($.cookies.get('exp_likes')));
	
	if (likes) {
		//likes = JSON.parse(likes);
		if (d) console.log(likes);
		var html = '';
		$.each(likes, function(key, val) {
			html += '<div><strong>' + val.name + '</strong><br>';
			if (d) console.log(typeof(val.color));
			if (val.style) {
				html += ' - Style: ' + val.style + '<br />';
			}
			if (val.color) {
				html += ' - Color: ' + val.color + '<br />';
			}
			if (val.window) {
				html += ' - Windows: ' + val.window + '<br />';
			}
			html +=	'</div>';
		});
		if (d) console.log(html);
		$('.doors_liked .list').html(html);
	} else {
		$('.doors_liked .list').html('<p align="center">You still don\'t like anything?</p>');
	}
};

var isObject = function (x) {
	return (typeof x === 'object') && !(x instanceof Array) && (x !== null);
};

/*
 * Request management code added
 * By: Jay Ward
 * Date: June 15, 2011
 * Purpose: Condense form elements into a single field for ease of storing and emailing.
 */

/* attach the request manager to form field updates on page load */
var hook_request_manager = function() {
    var form = "#request_more";
    $('input, select, textarea', form).each(
        function() {
            $(this).change(
                function() {
                    request_manager();
                }
            );
        }
    );
    return null;
}

/* Takes the contact request forms and manages all the options */
var request_manager = function() {  
    var form = "#request_more";
    var data = {};
    var ignore = {"address":"","city":"","email":"", "province":"", "name":"", "email":"", "phone1":"", "phone2":"", "":"", "preferences":""};
    var string = "\n";
    var toFill = $("#hidden_preferences");
    
    // Loops through all the form fields in the defined form
    $('input, select, textarea', form).each(
        function() {
            var el = $(this);
            var name = el.attr('name');
            var val = el.val();

            // Ignore hidden fields and any specified
            if (((!el.is(":hidden")) && (!(name in ignore))) || (name == "product_showroom")) {
            
                // Make sure to only grab the checkboxes which are selected
                if ((el.is(":checkbox")) && (!el.attr("checked"))) {
                    //console.log(el);
                } else {                
                    if (!data.hasOwnProperty(name)) {
                        data[name] = new Array;
                    }
                
                    data[name].push(val);
                }
            }
        }
    );
     
    // Take the data generated from the loop and turn it into a string
    for (name in data) {
        var value = data[name];
        string += name + ": " + value + "\n";
    }

    // Take the string and shove it into the hidden field  
    toFill.val(string);
    return null; 
}

