var product_id = null; 
var type_id = null;
var option_id = null;
var tabView = null;
var geocoder = null;
var order = null;
var quoteType = null;
//var googleKey = 'ABQIAAAAcB60xrqpvIB-f8fxSP9t8hSMIcRLyYf7KD1_SXy5jFJK2kTIHRQPpAD6BBp9_dG8O7gHhXihMbUxlQ';


// a global month names array
var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);

// a global day names array
var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);

/* PHP serialize/unserialize library.
 *
 * Copyright (C) 2006-2007 Ma Bingyao <andot@ujn.edu.cn>
 * Version: 3.1
 * LastModified: May 3, 2007
 * This library is free.  You can redistribute it and/or modify it.
 */

function utf16to8(str) {
    var out, i, len, c;

    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
	c = str.charCodeAt(i);
	if ((c >= 0x0001) && (c <= 0x007F)) {
	    out += str.charAt(i);
	} else if (c > 0x07FF) {
	    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
	    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
	    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	} else {
	    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
	    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
	}
    }
    return out;
}

function utf8to16(str) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = str.length;
    i = 0;
    while(i < len) {
	c = str.charCodeAt(i++);
	switch(c >> 4)
	{ 
	  case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
	    // 0xxxxxxx
	    out += str.charAt(i-1);
	    break;
	  case 12: case 13:
	    // 110x xxxx   10xx xxxx
	    char2 = str.charCodeAt(i++);
	    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
	    break;
	  case 14:
	    // 1110 xxxx  10xx xxxx  10xx xxxx
	    char2 = str.charCodeAt(i++);
	    char3 = str.charCodeAt(i++);
	    out += String.fromCharCode(((c & 0x0F) << 12) |
					   ((char2 & 0x3F) << 6) |
					   ((char3 & 0x3F) << 0));
	    break;
	}
    }

    return out;
}

function serialize(o) {
    var p = 0, sb = [], ht = [], hv = 1;
    var classname = function(o) {
        if (typeof(o) == 'undefined' || typeof(o.constructor) == 'undefined') return '';
        var c = o.constructor.toString();
        c = utf16to8(c.substr(0, c.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, ''));
        return ((c == '') ? 'Object' : c);
    };
    var is_int = function(n) {
        var s = n.toString(), l = s.length;
        if (l > 11) return false;
        for (var i = (s.charAt(0) == '-') ? 1 : 0; i < l; i++) {
            switch (s.charAt(i)) {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9': break;
                default : return false;
            }
        }
        return !(n < -2147483648 || n > 2147483647);
    };
    var in_ht = function(o) {
        for (var k in ht) if (ht[k] === o) return k;
        return false;
    };
    var ser_null = function() {
        sb[p++] = 'N;';
    };
    var ser_boolean = function(b) {
        sb[p++] = (b ? 'b:1;' : 'b:0;');
    };
    var ser_integer = function(i) {
        sb[p++] = 'i:' + i + ';';
    };
    var ser_double = function(d) {
        if (isNaN(d)) d = 'NAN';
        else if (d == Number.POSITIVE_INFINITY) d = 'INF';
        else if (d == Number.NEGATIVE_INFINITY) d = '-INF';
        sb[p++] = 'd:' + d + ';';
    };
    var ser_string = function(s) {
        var utf8 = utf16to8(s);
        sb[p++] = 's:' + utf8.length + ':"';
        sb[p++] = utf8;
        sb[p++] = '";';
    };
    var ser_date = function(dt) {
        sb[p++] = 'O:4:"Date":7:{';
        sb[p++] = 's:4:"year";';
        ser_integer(dt.getFullYear());
        sb[p++] = 's:5:"month";';
        ser_integer(dt.getMonth() + 1);
        sb[p++] = 's:3:"day";';
        ser_integer(dt.getDate());
        sb[p++] = 's:4:"hour";';
        ser_integer(dt.getHours());
        sb[p++] = 's:6:"minute";';
        ser_integer(dt.getMinutes());
        sb[p++] = 's:6:"second";';
        ser_integer(dt.getSeconds());
        sb[p++] = 's:11:"millisecond";';
        ser_integer(dt.getMilliseconds());
        sb[p++] = '}';
    }
    var ser_array = function(a) {
        sb[p++] = 'a:';
        var lp = p;
        sb[p++] = 0;
        sb[p++] = ':{';
        for (var k in a) {
            if (typeof(a[k]) != 'function') {
                is_int(k) ? ser_integer(k) : ser_string(k);
                __serialize(a[k]);
                sb[lp]++;
            }
        }
        sb[p++] = '}';
    };
    var ser_object = function(o) {
        var cn = classname(o);
        if (cn == '') ser_null();
        else if (typeof(o.serialize) != 'function') {
            sb[p++] = 'O:' + cn.length + ':"' + cn + '":';
            var lp = p;
            sb[p++] = 0;
            sb[p++] = ':{';
            if (typeof(o.__sleep) == 'function') {
                var a = o.__sleep();
                for (var kk in a) {
                    ser_string(a[kk]);
                    __serialize(o[a[kk]]);
                    sb[lp]++;
                }
            }
            else {
                for (var k in o) {
                    if (typeof(o[k]) != 'function') {
                        ser_string(k);
                        __serialize(o[k]);
                        sb[lp]++;
                    }
                }
            }
            sb[p++] = '}';
        }
        else {
            var cs = o.serialize();
            sb[p++] = 'C:' + cn.length + ':"' + cn + '":' + cs.length + ':{' +cs + '}';
        }
    };
    var ser_pointref = function(R) {
        sb[p++] = 'R:' + R + ';';
    };
    var ser_ref = function(r) {
        sb[p++] = 'r:' + r + ';';
    };
    var __serialize = function(o) {
        if (o == null || o.constructor == Function) {
            hv++;
            ser_null();
        }
        else switch (o.constructor) {
            case Boolean: {
                hv++;
                ser_boolean(o);
                break;
            }
            case Number: {
                hv++;
                is_int(o) ? ser_integer(o) : ser_double(o);
                break;
            }
            case String: {
                hv++;
                ser_string(o);
                break;
            }
            case Date: {
                hv++;
                ser_date(o);
            }
/*            case VBArray: {
                o = o.toArray();
            }
*/
            case Object:
            case Array: {
                var r = in_ht(o);
                if (r) {
                    ser_pointref(r);
                }
                else {
                    ht[hv++] = o;
                    ser_array(o);
                }
                break;
            }
            default: {
                var r = in_ht(o);
                if (r) {
                    hv++;
                    ser_ref(r);
                }
                else {
                    ht[hv++] = o;
                    ser_object(o);
                }
                break;
            }
        }
    };
    __serialize(o);
    return sb.join('');
}

function unserialize(ss) {
    var p = 0, ht = [], hv = 1;
    var unser_null = function() {
        p++;
        return null;
    };
    var unser_boolean = function() {
        p++;
        var b = (ss.charAt(p++) == '1');
        p++;
        return b;
    };
    var unser_integer = function() {
        p++;
        var i = parseInt(ss.substring(p, p = ss.indexOf(';', p)));
        p++;
        return i;
    };
    var unser_double = function() {
        p++;
        var d = ss.substring(p, p = ss.indexOf(';', p));
        switch (d) {
            case 'NAN': d = NaN; break;
            case 'INF': d = Number.POSITIVE_INFINITY; break;
            case '-INF': d = Number.NEGATIVE_INFINITY; break;
            default: d = parseFloat(d);
        }
        p++;
        return d;
    };
    var unser_string = function() {
        p++;
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        var s = utf8to16(ss.substring(p, p += l));
        p += 2;
        return s;
    };
    var unser_array = function() {
        p++;
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        var a = [];
        ht[hv++] = a;
        for (var i = 0; i < n; i++) {
            var k;
            switch (ss.charAt(p++)) {
                case 'i': k = unser_integer(); break;
                case 's': k = unser_string(); break;
                case 'U': k = unser_unicode_string(); break;
                default: return false;
            }
            a[k] = __unserialize();
        }
        p++;
        return a;
    };
    var unser_date = function() {
        var k, a = [];
        for (var i = 0; i < 7; i++) {
            p++;
            k = unser_string();
            p++;
            a[k] = unser_integer();
        }
        var dt = new Date(
            a['year'],
            a['month'] - 1,
            a['day'],
            a['hour'],
            a['minute'],
            a['second'],
            a['millisecond']
        );
        ht[hv++] = dt;
        return dt;
    }
    var unser_object = function() {
        p++;
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        var cn = utf8to16(ss.substring(p, p += l));
        p += 2;
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        if (cn == "Date" && n == 7) {
            return unser_date();
        }
        if (eval(['typeof(', cn, ') == "undefined"'].join(''))) {
            eval(['function ', cn, '(){}'].join(''));
        }
        var o = eval(['new ', cn, '()'].join(''));
        ht[hv++] = o;
        for (var i = 0; i < n; i++) {
            var k;
            switch (ss.charAt(p++)) {
                case 's': k = unser_string(); break;
                case 'U': k = unser_unicode_string(); break;
                default: return false;
            }
            if (k.charAt(0) == '\0') {
                k = k.substring(k.indexOf('\0', 1) + 1, k.length);
            }
            o[k] = __unserialize();
        }
        p++;
        if (typeof(o.__wakeup) == 'function') o.__wakeup();
        return o;
    };
    var unser_custom_object = function() {
        p++;
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        var cn = utf8to16(ss.substring(p, p += l));
        p += 2;
        var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        if (eval(['typeof(', cn, ') == "undefined"'].join(''))) {
            eval(['function ', cn, '(){}'].join(''));
        }
        var o = eval(['new ', cn, '()'].join(''));
        ht[hv++] = o;
        if (typeof(o.unserialize) != 'function') p += n;
        else o.unserialize(ss.substring(p, p += n));
        p++;
        return o;
    };
    var unser_unicode_string = function() {
        p++;
        var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
        p += 2;
        var sb = [];
        for (var i = 0; i < l; i++) {
            if ((sb[i] = ss.charAt(p++)) == '\\') {
                sb[i] = String.fromCharCode(parseInt(ss.substring(p, p += 4), 16));
            }
        }
        p += 2;
        return sb.join('');
    };
    var unser_ref = function() {
        p++;
        var r = parseInt(ss.substring(p, p = ss.indexOf(';', p)));
        p++;
        return ht[r];
    };
    var __unserialize = function() {
        switch (ss.charAt(p++)) {
            case 'N': return ht[hv++] = unser_null();
            case 'b': return ht[hv++] = unser_boolean();
            case 'i': return ht[hv++] = unser_integer();
            case 'd': return ht[hv++] = unser_double();
            case 's': return ht[hv++] = unser_string();
            case 'U': return ht[hv++] = unser_unicode_string();
            case 'r': return ht[hv++] = unser_ref();
            case 'a': return unser_array();
            case 'O': return unser_object();
            case 'C': return unser_custom_object();
            case 'R': return unser_ref();
            default: return false;
        }
    };
    return __unserialize();
}

function js_array_to_php_array (arr)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in arr)
    {
        ++ total;
		switch(typeof(arr[key]))
		{
			case "string":
				a_php = a_php + "s:" +
		                String(key).length + ":\"" + String(key) + "\";s:" +
		                String(arr[key]).length + ":\"" + String(arr[key]) + "\";";
			break;
			case "number": //for now also pass it as a number
				a_php = a_php + "s:" +
		                String(key).length + ":\"" + String(key) + "\";s:" +
		                String(arr[key]).length + ":\"" + String(arr[key]) + "\";";
			break;
			case "object":
				a_php = a_php + "s:" +
		                String(key).length + ":\"" + String(key) + "\";" + 
						js_array_to_php_array(arr[key]);
			break;
		}
        
    }
    a_php = "a:" + total + ":{" + a_php + "};";
    return a_php;
}

Number.prototype.zf = function(num)
{
	var totalDigitLeng = String(this).length;
	zeroToFill = num - totalDigitLeng;
	var ret = '';
	for(var i=0; i<zeroToFill; i++)
	{
		ret = ret + '0';
	}
	
	return ret + String(this);
}

// the date format prototype
Date.prototype.format = function(f)
{
    if (!this.valueOf())
        return '&nbsp;';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
            case 'yyyy': return d.getFullYear();
            case 'mmmm': return gsMonthNames[d.getMonth()];
            case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
            case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'dddd': return gsDayNames[d.getDay()];
            case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
            case 'dd':   return d.getDate().zf(2);
            case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case 'nn':   return d.getMinutes().zf(2);
            case 'ss':   return d.getSeconds().zf(2);
            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
}

/*Price calculating functions*/
function get_first28_rent_price()
{
	var price = products[product_id]['types'][type_id]['price'];
	if(option_id)
		price = price + products[product_id]['types'][type_id]['options'][option_id]['price'];
	
	return price; 
}
function get_purchase_price()
{
	var price = products[product_id]['types'][type_id]['price'];
	if(option_id)
		price = price + products[product_id]['types'][type_id]['option'][option_id]['price'];
	
	return price; 
}
function get_recurring_rent_price()
{
	var price = products[product_id]['types'][type_id]['price'];
	if(option_id)
		price = price + products[product_id]['types'][type_id]['options'][option_id]['price'];
	
	return price; 
}
function get_transportation_charge(destination_zip,base_price,free_distance,max_distance,price_per_mile,locations) 
{
	var min_distance = 99999999999999;
	var location_index = null;
	
	if (locations.constructor.toString().indexOf('Array') == -1)
	{
		//the passed parameter is a single zip number
		var distance = calculate_distance(locations, destination_zip );
		
		if(distance < min_distance)
		{
			min_distance = distance;
			location_index = i
		}
	}
	else
	{
		//the passed parameter is an array of locations
		for(var i=0; i<locations.length; i++)
		{
			var distance = calculate_distance(locations[i]['zip'], destination_zip );
			if(distance < min_distance)
			{
				min_distance = distance;
				location_index = i
			}
		}
	}
	
	
	if(min_distance < free_distance)
	{
		if(parseInt(base_price) == base_price)
			return base_price
		else
			return parseInt(base_price) + 1;
	}
	else if(min_distance < max_distance)
	{
		var res = base_price + ( (min_distance - free_distance) * price_per_mile )
		
		if(parseInt(res) == res)
			return res
		else
			return parseInt(res) + 1;
		
	}
	
	//outside delivery area
	return false;
}
function get_location_charge(destination_zip,location_charge,locations,free_location_zip)
{
	var min_distance = 99999999999999;
	var location_index = null;
	for(var i=0; i<locations.length; i++)
	{
		var distance = calculate_distance(locations[i]['zip'], destination_zip );
		if(distance < min_distance)
		{
			min_distance = distance;
			location_index = i
		}
	}
	
	if(locations[location_index]['zip'] == free_location_zip)
	{
		return 0;
	}
	else
	{
		return location_charge;
	}
}
function get_quote()
{
	//we need a cache for the same zips
	
	var url = '/wizard/quote.php?action=get';
	var xmlhttp = null;
	var num = null;
	
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp = false;
	  }
	 }
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	
	if (xmlhttp)
	{
	  xmlhttp.open('GET', url, false);
	  xmlhttp.send(null);
	  num = parseInt(xmlhttp.responseText);
	}
	
	num = num+1+50;
	var qn = (new Date()).format('yyyymmdd');
	qn = qn + '-' + num
	return qn;
}
function sum_above(current_index)
{
	var sum = 0 
	for(var k=0; k<current_index; k++)
	{
		if(option_id) var str = products[product_id]['types'][type_id]['options'][option_id]['price_table'][k]['func'];
		else		  var str = products[product_id]['types'][type_id]['price_table'][k]['func'];
		
		sum = sum + eval(str);
	}
	return sum;
}
function calculate_distance(zip1, zip2)
{
	//we need a cache for the same zips
	
	var url = '/wizard/distance.php?zip1='+zip1+'&zip2='+zip2;
	var xmlhttp = null;
	var distance = null;
	var doc = null;
	
	
	
	if(distance_cache[zip1.toString()+zip2.toString()])
		return distance_cache[zip1.toString()+zip2.toString()]
	
	
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   xmlhttp = false;
	  }
	 }
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp=false;
		}
	}
	
	if (xmlhttp)
	{
	  xmlhttp.open('GET', url, false);
	  xmlhttp.send(null);
	  distance = parseInt(xmlhttp.responseText);
	}
	
	//incrise the distance by 20%
	distance = parseInt( distance + (distance * 20 / 100));
	
	distance_cache[zip1.toString()+zip2.toString()] = distance;
	return distance;
}

/*
function get_tracking_pixel()
{
		
	var url = '/wizard/pixel.php';
	var callback = 
	{ 
		  success: function(o) {}, 
		  failure: function(o) {}		  
	}
	var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null); 	
}
*/

function handleTabChange(e) 
{
	
	
	var tab_index = tabView.getTabIndex(e.newValue);
	
	
	switch(tab_index)
	{
		case 1: //Type
			if(!product_id) //Product was not selected
			{
				//send the user back
				alert('You have to select a product first');
				//tabView.set('activeIndex', 0);
				return false;
				
			}
			else if(!type_id) //Type was not yet seleced so we have to init it
			{
				init_types();
			}
		break;
		case 2: //Delivery
			if(!product_id) //Product was not selected
			{
				//send the user back
				alert('You have to select a product first');
				//tabView.set('activeIndex', 0);
				return false;
			}
			else if(!type_id) //Type was not yet seleced so we have to init it
			{
				//send the user back
				alert('You have to select a type first');
				//tabView.set('activeIndex', 1);
				return false;
			}
			else if(!option_id && products[product_id]['types'][type_id]['options'])
			{
				//send the user back
				alert('You have to select a option first');
				//tabView.set('activeIndex', 1);
				return false;
			}
			else if(option_id)
			{
				//all ok, check if this is a special type
				if(products[product_id]['types'][type_id]['options'][option_id]['type'] == 2)
					document.getElementById('zip2_container').style.display = 'block';
				else
					document.getElementById('zip2_container').style.display = 'none';
			}
			else
			{
				document.getElementById('zip2_container').style.display = 'none';
			}
			init_delivery();
		break;
		case 3: //Price
			if(!product_id) //Product was not selected
			{
				//send the user back
				alert('You have to select a product first');
				//tabView.set('activeIndex', 0);
				return false;
			}
			else if(!type_id) //Type was not yet seleced so we have to init it
			{
				//send the user back
				alert('You have to select a type first');
				//tabView.set('activeIndex', 1);
				return false;
			}
			else if(!option_id && products[product_id]['types'][type_id]['options'])
			{
				//send the user back
				alert('You have to select a option first');
				//tabView.set('activeIndex', 1);
				return false;
			}
			else if(!validate_zip())
			{
				alert('Please enter a valid Zip Code for delivery');
				//tabView.set('activeIndex', 2);
				return false;
			}
			else if(!validate_date())
			{
				alert('Please select a delivery date');
				//tabView.set('activeIndex', 2);
				return false;
			}
			
			return init_price();
			
		break;
		case 4: //Contact info
			if(!order) return false;
			else
			{
				init_contact();
			} 
			return true;
		break;
	}
	
};
function get_active_tab()
{
	var tabs = tabView.get('tabs');

	for(var i=0;i<tabs.length;i++)
	{
		if(tabs[i].get('active'))
			return i;
	}
	return null;
}


function validate_zip()
{
	var zip = document.getElementById('zip').value;
	reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);

	if (!reZip.test(zip))
		return false;
	else
		return true;
}
function validate_date()
{
	var date = document.getElementById('date');
	if(date.value.length > 0)
		return true
	else
		return false;
}
function handleCalendarSelect(type,args,obj) 
{
				var dates = args[0]; 
				var date = dates[0];
				var year = date[0], month = date[1], day = date[2];

				var txt_date = document.getElementById("date");
				txt_date.value = month + "/" + day + "/" + year;
}

/* Button actions */
function click_next(e) 
{
		var activ_tab = get_active_tab();
		tabView.set('activeIndex', activ_tab + 1);
}
function click_prev(e) 
{
		var activ_tab = get_active_tab();
		tabView.set('activeIndex', activ_tab - 1);
}
function fReserv(e) 
{
		var activ_tab = get_active_tab();
		quoteType = 1;
		tabView.set('activeIndex', activ_tab + 1);
		
}
function fEmailQuote(e) 
{
	var activ_tab = get_active_tab();
	quoteType = 2;
	tabView.set('activeIndex', activ_tab + 1);
	
}
function fQuestions(e) 
{
		var activ_tab = get_active_tab();
		quoteType = 3;
		tabView.set('activeIndex', activ_tab + 1);
		
}

function post_data()
{
	var first_name = document.getElementById('first_name');
	var last_name = document.getElementById('last_name');
	var company_name = document.getElementById('company_name');
	var email_address = document.getElementById('email_address');
	var phone_number = document.getElementById('phone_number');
	var message = document.getElementById('message');
	var Campaign_ID = document.getElementById('Campaign_ID');
	
	/* reset all border	*/
	first_name.style.border = '';
	last_name.style.border = '';
	company_name.style.border = '';
	email_address.style.border = '';
	phone_number.style.border = '';
		
	var errors = false;
	
	if(first_name.value.length<2) {first_name.style.border = '2px solid red';errors = true;} 
	if(last_name.value.length<2) {last_name.style.border = '2px solid red';errors = true;} 
	//if(company_name.value.length<2) {company_name.style.border = '2px solid red';errors = true;} 
	if(email_address.value.length<4) {email_address.style.border = '2px solid red';errors = true;} 
	if(phone_number.value.length<2) {phone_number.style.border = '2px solid red';errors = true;}
	
	if(errors)
	{
		alert('Please complete all required fields');
		return false;
	} 
	
	order['first_name'] = first_name.value;
	order['last_name'] = last_name.value;
	order['company_name'] = company_name.value;
	order['email_address'] = email_address.value;
	order['phone_number'] = phone_number.value;
	order['message'] = message.value;
	order['Campaign_ID'] = Campaign_ID.value;
	
	
	switch(quoteType)
	{
		case 1:
		order['type'] = 'Reservation';
		break
		case 2:
		order['type'] = 'Email Quote';
		break;
		case 3:
		order['type'] = 'Inquiry';
		break;
	}

	
	order['product_id'] = product_id;
	order['type_id'] = type_id;
	order['option_id'] = option_id;
	
	//alert(js_array_to_php_array(order));
	//document.write(js_array_to_php_array(order));
	//all data is ready to be send now in the "order" array
	

	 
	var AjaxObject = {  
	 
	    handleSuccess:function(o){  
	        // This member handles the success response  
	        // and passes the response object o to AjaxObject's  
	        // processResult member.  
	        //this.processResult(o);  
			//alert('Data Submited');
			switch(product_id)
			{
				case "0":
					window.location = "/thank_you_Falcon_Box_Rental.html";
				break;
				case "1":
					window.location = "/thank_you_GoMini_Rental.html";
				break;
				case "2":
					window.location = "/thank_you_Falcon_Building_Rental.html";
				break;
				case "3":
					window.location = "/thank_you_Box_Purchase.html";
				break;
				
				
			}
			//window.location = '/thank_you/'
	    },  
	 
	    handleFailure:function(o){  
	        // Failure handler  
	    },  
	 		    	 
	    startRequest:function() {  
	       //document.getElementById('form_submit').disable = true;
		   YAHOO.util.Connect.asyncRequest('POST', '/wizard/post.php', callback, "order="+serialize(order));
	  
	    }  
	 
	};  
	 
	/* 
	 * Define the callback object for success and failure 
	 * handlers as well as object scope. 
	 */  
	var callback =  
	{  
	    success:AjaxObject.handleSuccess,  
	    failure:AjaxObject.handleFailure,  
	    scope: AjaxObject  
	};  
	 
	// Start the transaction.  
	AjaxObject.startRequest();
}

/*Tab init functions*/
function init() 
{
	//geocoder = new GClientGeocoder();
	tabView = new YAHOO.widget.TabView('wizard');
	tabView.set('activeIndex', 0);
	//tabView.addListener('activeTabChange', handleTabChange);
	tabView.addListener('beforeActiveTabChange', handleTabChange);
	//var tab_type = tabView.getTab(1);
	//tab_type.on('beforeActiveChange', handleTypeTabChange);
	//var tab_delivery = tabView.getTab(2);
	//tab_delivery.on('beforeActiveChange', handleDeliveryTabChange);
	//var tab_price = tabView.getTab(3);
	//tab_price.on('beforeActiveChange', handlePriceTabChange);
	
	today = new Date()
	calendar = new YAHOO.widget.Calendar("calendar","calendar_container", { mindate:today });
	calendar.selectEvent.subscribe(handleCalendarSelect, calendar, true);
	calendar.render();


	var product_next = new YAHOO.widget.Button("product_next", { id:"product_next_new" } );
	product_next.on("click", click_next);

	var type_next = new YAHOO.widget.Button("type_next", { id:"type_next_new" } );
	type_next.on("click", click_next);
	
	var delivery_next = new YAHOO.widget.Button("delivery_next", { id:"delivery_next_new" } );
	delivery_next.on("click", click_next);
	
	
	var type_prev = new YAHOO.widget.Button("type_prev", { id:"type_prev_new" } );
	type_prev.on("click", click_prev);
	
	var delivery_prev = new YAHOO.widget.Button("delivery_prev", { id:"delivery_prev_new" } );
	delivery_prev.on("click", click_prev);
	
	var price_prev = new YAHOO.widget.Button("price_prev", { id:"price_prev_new" } );
	price_prev.on("click", click_prev);
	
	var contact_prev = new YAHOO.widget.Button("contact_prev", { id:"contact_prev_new" } );
	contact_prev.on("click", click_prev);
	
	var reserv = new YAHOO.widget.Button("reserv", { id:"reserv_new" } );
	reserv.on("click", fReserv);

	var emailQuote = new YAHOO.widget.Button("email_quote", { id:"email_quote_new" } );
	emailQuote.on("click", fEmailQuote);
	
	var questions = new YAHOO.widget.Button("questions", { id:"questions_new" } );
	questions.on("click", fQuestions);
	
	var submit = new YAHOO.widget.Button("form_submit", { id:"form_submit_new" } );
	submit.on("click", post_data);
	
	
	
	
	//init_types();
	init_products();
};
function init_products()
{
	var container = document.getElementById('product_container');
	for( i=0; i<products.length; i++ )
	{
		if( navigator.userAgent.indexOf('MSIE') == -1 )
		{
			
			var radio = document.createElement('input');
			radio.type = 'radio';
			radio.name = 'product_id';
			radio.value = i;
			radio.id = 'product_'+i;
		}
		else
		{
			//workaround for an ugly IE bug
			var radio = document.createElement('<input type="radio" name="product_id" value="'+i+'" id="product_'+i+'">');
		}
		
		var label = document.createElement('label');
		label.htmlFor = 'product_'+i
		var caption = document.createTextNode(products[i]['name']);
		label.appendChild(caption);
		var br = document.createElement('br');
		
		container.appendChild(radio);
		container.appendChild(label);
		container.appendChild(br);
		
		var el = new YAHOO.util.Element('product_'+i);  
		el.on('click', function(e) { 
				//debugger;
				product_id = YAHOO.util.Event.getTarget(e).value; 
				type_id = null; 
				option_id = null;	
				});
	}
	
	//create the options container			
}
function init_types()
{
	var container = document.getElementById('type_container');
	var title = document.getElementById('type_title');
	title.innerHTML = 'What type of '+products[product_id]['name']+'?';
	while (container.hasChildNodes())
	{
		container.removeChild(container.firstChild);
	}
	var o_container = document.getElementById('options_container');
	while (o_container.hasChildNodes())
	{
		o_container.removeChild(o_container.firstChild);
	}
	var o_title = document.getElementById('options_title');
	o_title.innerHTML = '';
	for( i=0; i<products[product_id]['types'].length; i++ )
	{
		if( navigator.userAgent.indexOf('MSIE') == -1 )
		{
			
			var radio = document.createElement('input');
			radio.type = 'radio';
			radio.name = 'type_id';
			radio.value = i;
			radio.id = 'type_'+product_id+'_'+i;
		}
		else
		{
			//workaround for an ugly IE bug
			var radio = document.createElement('<input type="radio" name="type_id" value="'+i+'" id="type_'+product_id+'_'+i+'">');
		}
		
		var label = document.createElement('label');
		label.htmlFor = 'type_'+product_id+'_'+i;
		var caption = document.createTextNode(products[product_id]['types'][i]['name']);
		label.appendChild(caption);
		var br = document.createElement('br');
		
		container.appendChild(radio);
		container.appendChild(label);
		container.appendChild(br);
		
		var el = new YAHOO.util.Element('type_'+product_id+'_'+i);  
		el.on('click', function(e) 
			{ 
				type_id = e.target.value; option_id = null; 
				if(products[product_id]['types'][type_id]['options']) 
				{
					init_options();	
				}
				else
				{
					//clear the options container
					var container = document.getElementById('options_container');
					while (container.hasChildNodes())
					{
						container.removeChild(container.firstChild);
					}	
					var title = document.getElementById('options_title');
					title.innerHTML = '';
				}
			}
		);
	}			
}
function init_options()
{
	document.getElementById('opt').style.display = 'block';
	var container = document.getElementById('options_container');
	while (container.hasChildNodes())
	{
		container.removeChild(container.firstChild);
	}
	var title = document.getElementById('options_title');
	title.innerHTML = products[product_id]['types'][type_id]['options_title'];
	for( i=0; i<products[product_id]['types'][type_id]['options'].length; i++ )
	{
		if( navigator.userAgent.indexOf('MSIE') == -1 )
		{
			
			var radio = document.createElement('input');
			radio.type = 'radio';
			radio.name = 'option_id';
			radio.value = i;
			radio.id = 'option_'+product_id+'_'+type_id+'_'+i;
		}
		else
		{
			//workaround for an ugly IE bug
			var radio = document.createElement('<input type="radio" name="option_id" value="'+i+'" id="option_'+product_id+'_'+type_id+'_'+i+'">');
		}
		
		
		var label = document.createElement('label');
		label.htmlFor = 'option_'+product_id+'_'+type_id+'_'+i;
		var caption = document.createTextNode(products[product_id]['types'][type_id]['options'][i]['name']);
		label.appendChild(caption);
		var br = document.createElement('br');
		
		container.appendChild(radio);
		container.appendChild(label);
		container.appendChild(br);
		
		var el = new YAHOO.util.Element('option_'+product_id+'_'+type_id+'_'+i);  
		el.on('click', function(e) 
			{ 
				option_id = e.target.value;  
			}
		);
	}			
}
function init_delivery()
{
	var title = document.getElementById('delivery_title');
	title.innerHTML = 'You have selected a '+products[product_id]['name']+' ('+	products[product_id]['types'][type_id]['name']+')';
	
	if(products[product_id]['types'][type_id]['options']) 
	{
		title.innerHTML = title.innerHTML + ' '+ products[product_id]['types'][type_id]["options_title"].replace(/ I /," you ") + ' ' + products[product_id]['types'][type_id]['options'][option_id]['name'].replace(/my/,"your");
	}
	
	
	
}
function init_price()
{
	var title = document.getElementById('price_title');
	order = new Array();
	title.innerHTML = 'You have selected a '+products[product_id]['name']+' ('+	products[product_id]['types'][type_id]['name']+') for delivery to '+document.getElementById('zip').value+ '.  Desired delivery date is '+document.getElementById('date').value+'.';
	order['title'] = title.innerHTML;
	
	if(products[product_id]['types'][type_id]['options']) 
	{
		title.innerHTML = title.innerHTML + ' '+ products[product_id]['types'][type_id]["options_title"].replace(/ I /," you ") + ' ' + products[product_id]['types'][type_id]['options'][option_id]['name'].replace(/my/,"your");
		
		if(products[product_id]['types'][type_id]['options'][option_id]['type'] == 2)
		{
			title.innerHTML = title.innerHTML + ' (Zip Code '+document.getElementById('zip2').value+'). Once you have unpacked it, we will pick it up.'; 
			
		}
		
	}
	order['title'] = title.innerHTML;
	//order['title'] .= '<br />'; 
	order['zip'] = document.getElementById('zip').value;
	order['date'] = document.getElementById('date').value;
	
	var container = document.getElementById('price_container');
	order['quote#'] = get_quote();
	document.getElementById('quote').innerHTML = order['quote#'];
	while (container.hasChildNodes())
	{
		container.removeChild(container.firstChild);
	}
	
	if(option_id)
		var fields = products[product_id]['types'][type_id]["options"][option_id]['price_table'];
	else
		var fields = products[product_id]['types'][type_id]['price_table'];
	
	order['price_components'] = new Array()
	for(var j=0; j<fields.length; j++)
	{
		var label = document.createElement('div');
		var caption = document.createTextNode(fields[j]['name']);
		label.appendChild(caption);
		label.className = "label";
		
		var value = document.createElement('div');
		value.className = "value";
		
		var val = eval(fields[j]['func']);
		if(val)
		{
			var _val = document.createTextNode('$'+val);
			value.appendChild(_val);
			order['price_components'][j] = new Array();
			order['price_components'][j]['name'] = fields[j]['name'];
			order['price_components'][j]['value'] = val;
		}
		else
		{
			//reset the order obj
			order = null;
			alert(fields[j]['err']);
			//tabView.set('activeIndex', 2);
			return false;
			
			
		}
		
		
	
		var br = document.createElement('br');
		
		if(fields[j]['func'].indexOf('sum') != -1)
		{
			var hr = document.createElement('hr');
			container.appendChild(hr);
		}
		container.appendChild(label);
		container.appendChild(value);
		container.appendChild(br);
		
		
		if(fields[j]['func'].indexOf('sum') != -1)
		{
			var div = document.createElement('div');
			div.className = "spacer";
			container.appendChild(div);
		}
		
	}
	
	//record the generated quote
	order['product_id'] = product_id;
	order['type_id'] = type_id;
	order['option_id'] = option_id;
	
	//alert(js_array_to_php_array(order));
	//document.write(js_array_to_php_array(order));
	//all data is ready to be send now in the "order" array
	

	 
	var AjaxObject = {  
	 
	    handleSuccess:function(o){  
	        // This member handles the success response  
	        // and passes the response object o to AjaxObject's  
	        // processResult member.  
	        //this.processResult(o);  
			//alert('Data Submited');
			
	    },  
	 
	    handleFailure:function(o){  
	        // Failure handler  
	    },  
	 		    	 
	    startRequest:function() {  
	       //document.getElementById('form_submit').disable = true;
		   YAHOO.util.Connect.asyncRequest('POST', '/wizard/post.php', callback, "order="+serialize(order));
	  
	    }  
	 
	};  
	 
	/* 
	 * Define the callback object for success and failure 
	 * handlers as well as object scope. 
	 */  
	var callback =  
	{  
	    success:AjaxObject.handleSuccess,  
	    failure:AjaxObject.handleFailure,  
	    scope: AjaxObject  
	};  
	 
	// Start the transaction.  
	AjaxObject.startRequest();
	
	//now we need to request the tracking pixel 
	urchinTracker("/price_tab.html");
	return true;
	
}
function init_contact()
{
	switch (quoteType)
	{
		case 1: //reservation
			document.getElementById('contact_title').innerHTML = 'Make a Reservation'
			document.getElementById('contact_description').innerHTML =  'We can usually deliver with 48 hour notice.  Someone will contact you to confirm the availability of the reservation once you have submitted this form. Thanks!';
		break;
		case 2: //email quote
			document.getElementById('contact_title').innerHTML = 'Email quote for your records';
			document.getElementById('contact_description').innerHTML =  'Please fill out the following fields so that we can email you the quote. If this is an emergency, please contact us at 866-325-2665 x1. Thanks!';
		break;
		case 3:  //inquiry
			document.getElementById('contact_title').innerHTML = 'Contact us with questions';
			document.getElementById('contact_description').innerHTML =  'Please fill out the following form and one of our advisors will contact you to answer any additional questions you have. If this is a storage emergency, please call us at 866-325-2665 x1. Thanks!';
		break;
	}
	
	
}


YAHOO.util.Event.addListener(this,"load",init);