/**
 * @author Henry
 */

popupH = 540;
popupW = 730;
winRef = null;
filtersChanged = false;

function indexPopups() {
	var popupLinks = $$('a[rel^="popup"]');
	//var links = $A(document.getElementsByTagName("a"));
	popupLinks.each( function(link) {
		Event.observe(link, 'click', function(e) {
			popupFunction(e);
		});
	});
}

popupFunction = function (e){
	Event.stop(e);
	try {
		var el = Event.findElement(e, 'a');
		if (el != document) {
			var arr = el.getAttribute("rel").split(" ");
			var href = el.getAttribute("href");
			if (arr && href) {
				var pH = popupH;
				var pW = popupW;
				var sW = screen.width;
				var sH = screen.height;
				if (arr.length > 1) {
					pH = arr[1];
					pW = arr[2];
				}
				var top = parseInt((sH - pH)/2);
				var left = parseInt((sW - pH)/2);
				var features = "status=no,scrollbars=yes,"+"height="+pH+",width="+pW+",top="+top+",left="+left;
				winRef = window.open(href,"popup",features)
				winRef.focus();
			}
		}
	} catch(e) {}
}

var prepMenu = function() {
	try {
		['submenu0','submenu1','submenu2'].each(function(item, index) {

			new Effect.BlindUp($(item), {duration:0.0, afterFinish: restoreVisibility});
			var params = {duration:0.1, transition: Effect.Transitions.linear};

			Event.observe($('nav_in_'+index), 'mouseenter', function(e) {
				new Effect.BlindDown($(item), params);
				$('nav_out_'+index).style.background = '#fff';
			}.bindAsEventListener(this));

			Event.observe($('nav_in_'+index), 'mouseleave', function(e) {
				new Effect.BlindUp($(item), params);
				/* TO-DO: remove dependence on image path here */
				$('nav_out_' + index).style.backgroundImage = 'url(images/bg_mainnav_li.gif)';
			}.bindAsEventListener(this));

			// restore visibility submenu elements
			function restoreVisibility(obj){
				$(obj.element).removeClassName('invisible');
				$('nav_in_0').select('div.submenuposition')[0].removeClassName('invisible');
			}

		}.bind(this));
	} catch(e) {/* fail quietly */}
};

var isSafari = (Prototype.Browser.WebKit);

document.observe("dom:loaded", function() {
	prepMenu();
	indexPopups();
	processCompareTables();


	/*search stuff*/
	var distLinks = $$('div.alert a');
	if(distLinks){
        distLinks.each(function(distLink){
            Event.observe(distLink, 'click', function(e){
                Event.stop(e);
                document.forms[0].action = distLink.getAttribute('rel');
                document.forms[0].submit();
            });
        });
    }
	/*reset any checked boxes for comparison list*/
	var compareList = $('CL');
	if(compareList){
	    var action = $$('div.actions-bottom ul li')[0];

	    if(typeof action != 'undefined'){
    	    var count = 0;
		    var indexes = compareList.value.split(',');
		    if (compareList.value !== "") {
			    for(var i = 0; i < indexes.length; i++){
				    var el = $(indexes[i]);
				    if(el){
					    if(!el.checked)
						    el.checked = true;
						    count++;
				    }
			    }
		    }
		    var cars = (count == 1) ? "car" : "cars";
		    action.update(count + " " + cars + " checked");
		 }
	}
	
	var rangeState = $('Rs');
	if(rangeState)
	{
	    resetDropDowns($F('Rs'));
	}

	var compareBtn = $$('li.compare-checked a')[0];
	if(compareBtn)
	{
	    Event.observe(compareBtn, 'click', function(e){
	        Event.stop(e);
	        document.forms[0].action = compareBtn.getAttribute('href') + $('CL').getValue();
	        $('__VIEWSTATE').name = 'IGNORE';
	        $('__EVENTTARGET').name = '__METOO';
	        $('__EVENTARGUMENT').name = '__METHREE';
	        document.forms[0].submit();
	    });
	}

	var clearBtn = $$('li.clear-all')[0];
	if(clearBtn)
	{
	    Event.observe(clearBtn, 'click', function(e){
	        Event.stop(e);
	        $('CL').value = '';
	        var checkBoxes = $$('.car-search-result input');
	        checkBoxes.each(function(cb){if(cb.checked)cb.checked=false;});
	        $$('div.actions-bottom ul li')[0].update("0 cars checked");
	    });
	}

	var views = $$('a.view');
	views.each(function(view){
		Event.observe(view, 'click', function(e){
			var url = view.getAttribute('rel');
			document.forms[0].action = url;
			document.forms[0].submit();
		}.bind(this));
	});

	var sort = $('ddlSort');
	if(sort){
		Event.observe(sort, 'change', function(e){
			Event.stop(e);
			document.forms[0].action = sort.options[sort.selectedIndex].value;
			document.forms[0].submit();
		});
	}

	var distance = $('ddlDist');
	if(distance){
	    Event.observe(distance, 'change', function(e){
	        Event.stop(e);
	        gs('', distance.options[distance.selectedIndex].value);
	    });
	}


	/* Search filter form submits */
	var formSubmits = $$('td.tcol-2');
	formSubmits.each(function(el){
		var link = $(el).getElementsByTagName('a')[0];
		if (link) {
			Event.observe(link, 'click', function(e){
				Event.stop(e);
				var filterString = "";
				if(filtersChanged)
				{
				    filterString = buildFilterString();
				}
				document.forms[0].action = link.getAttribute('rel') + $('free_text').getValue() + filterString;
				document.forms[0].submit();
			})
		}
	});
	
	var filters = $$('ul.formInteriorContainer select');
	filters.each(function(filter){
	    Event.observe(filter, 'change', function(e){
	        Event.stop(e);
	        toggleFilter(true);
	    });
	});

	var getLinks = $$('table.criteria-table a[rel]', 'div.refine-block ul li a[rel]');
	getLinks.each(function(el){
		Event.observe(el, 'click', function(e){
			Event.stop(e);
			gs('', el.getAttribute('rel'));
		});
	});

	/*end search stuff*/


/* Perform tweaks required for Safari only */
	if (isSafari) {
		$('globalNav').select('a').each (function(item) {
			item.style.paddingBottom = "9px";
		});
	}
/* add event handlers for MyCarMax sign-in */
	var el_login = $("myCarMax_login");
	if (el_login) {
		Event.observe(el_login, 'click',function(e) {
			Event.stop(e);
			login_widget();
		});
	}
	var el_login_close = $("myCarMax_close");
	if (el_login_close) {
		Event.observe(el_login_close, 'click', function(e) {
			Event.stop(e);
			login_widget();
		});
	}
	login_widget(true);

	/* add event handlers for company info open/close sections */
	var profiles = $$('div.profileHeader');
	profiles.each(function(profile){
		var cell = profile.select('ul')[0];
		var span = profile.next();
		var image = $(cell).select('img')[0];

		Event.observe($(cell), 'click', function(e){
			Event.stop(e);
			if(span.hasClassName("branch-open")) {
				image.src = openImg.src;
			} else {
				image.src = closedImg.src;
			}
			span.toggleClassName("branch-open");
			cell.toggleClassName("blue");
		});
	});

	/* add event handlers for Search Page open/close sections - added by JN */
	var refine_blocks = $$('div.refine-block');
	refine_blocks.each(function(refine_block){
		var block = refine_block.select('h4')[0];
		Event.observe($(block), 'click', function(e){
			Event.findElement(e, 'div').toggleClassName('open');
			if(Event.findElement(e, 'div').hasClassName('open')){
			    var openList = ($('O').value === "") ? [] : $('O').value.split(',');
			    var x = Event.findElement(e, 'a').getAttribute('rel');
			    if(openList.indexOf(x) != -1)
			        var openList = openList.without(x);
			    $('O').value = (openList.length === 1) ? x : openList.join(',');
			    
			}
			else{
			    var openList = ($('O').value === "") ? [] : $('O').value.split(',');
			    var x = Event.findElement(e, 'a').getAttribute('rel');
			    if(openList.indexOf(x) == -1)
			        openList.push(x);			        
			    $('O').value = (openList.length === 1) ? x : openList.join(',');
			    
			   
			}
			Event.stop(e);
		});
	});

	/* Search filter form submits */
//	var formSubmits = $$('td.tcol-2');
//	formSubmits.each(function(el){
//		var link = $(el).getElementsByTagName('a')[0];
//		if (link) {
//			Event.observe($(link), "click", function(e){
//				Event.stop(e);
//				document.forms[0].submit();
//			})
//		}
//	});

	/* Location-changing select elements */
	var locationSelects = $$('select.locationSelector');
	locationSelects.each(function(select){
		Event.observe($(select), "change", function(e){
			selectRedirect(this);
		})
	});

	/* Find a car results highlights */
	var findCarResults = $$('.car-search-result');
	findCarResults.each(function(el){

		Event.observe(el, "mouseover", function(e){
			this.addClassName('highlighted');
		});

		Event.observe(el, "mouseout", function(e){
			this.removeClassName('highlighted');
		});

		Event.observe(el, 'click', function(e){
			var target = Event.element(e);
			if (target.tagName && target.tagName.toLowerCase() == "input") {
				var comparisonList = ($('CL').value === "") ? [] : $('CL').value.split(',');
				var x = target.getAttribute('id');
				if(target.checked){
					if(comparisonList.indexOf(x) == -1){
						comparisonList.push(x);
					}
					$('CL').value = (comparisonList.length === 1) ? x : comparisonList.join(',');
				} else {
					if(comparisonList.indexOf(x) != -1){
						var comparisonList = comparisonList.without(x);
					}
					$('CL').value = (comparisonList.length === 0) ? "" : comparisonList.join(',');
				}
				var cars = (comparisonList.length == 1) ? "car" : "cars";
				$$('div.actions-bottom ul li')[0].update(comparisonList.length + " " + cars + " checked");
			}
			else {
				Event.stop(e);
				var link = el.select('a[rel^="index:"]')[0];
				if (link) {
					var rel = link.getAttribute("rel");
					var index = link.getAttribute("rel").replace(/index:/,"");
					gs('/enUS/view-car/default.html', index);
				}
			}
		});
	});

	/* promotion tag links */
	//info-content:
	var hoverInfoLinks = $$('a[rel^="info-content:"],img[rel^="info-content:"]');
	if (hoverInfoLinks) {
		// create info elements
		var container = document.createElement("div");
		container.className = "info-box-container hide";
		var inner = document.createElement("div");
		inner.className = "info-box-inner";
		var cap = document.createElement("div");
		cap.className = "info-cap";
		var box = document.createElement("div");
		box.className = "info-box";
		// concatenate
		inner.appendChild(cap);
		inner.appendChild(box);
		container.appendChild(inner);
		// create globally available instance of info container
		infoContainer = document.body.appendChild(container);

		// attach event handlers to links
		hoverInfoLinks.each(function(link){
			Event.observe(link, 'mouseover', function(e){
				// process content of rel attribute
				var el = Event.findElement(e, 'a');
			    if (el == null)
				    el = Event.findElement(e, 'img');
				var content = el.getAttribute("rel").replace(/info-content:/,"");
				var paragraphs = content.split("|");
				if (paragraphs) {
					var contentEl = $(infoContainer).select('.info-box')[0];
					contentEl.innerHTML = "";
					paragraphs.each(function(p){
						var el = document.createElement("p");
						if (p.indexOf("{B}")==0) {
							p = p.replace(/{B}/,"");
							var b = document.createElement("strong");
							b.innerHTML = p;
							el.appendChild(b);
						} else {
							el.innerHTML = p;
						}
						contentEl.appendChild(el);
					});
					// retrieve location, size of link element
					var thisPos = el.cumulativeOffset();
					var thisX = thisPos.left;
					var thisY = thisPos.top;
					var thisSize = el.getDimensions();
					var thisW = thisSize.width;
					var thisH = thisSize.height;

					infoContainer.removeClassName("hide");
					infoContainer.setStyle({opacity:0, zindex:1000});
					var infoSize = infoContainer.getDimensions();
					var infoW = infoSize.width;
					var offset = (Prototype.Browser.IE) ? 15 : 10;
					infoContainer.style.left = thisX - parseInt(infoW/2,10) + parseInt(thisW/2,10) + "px"
					infoContainer.style.top = thisY + thisH + offset + "px";
					new Effect.Appear(infoContainer, {duration:0.1});
				}
				Event.stop(e);
			});
			Event.observe(link, 'mouseout', function(e){
				new Effect.Fade(infoContainer, {duration:0.1});
			});
		});
	}

	/* input type=image rollover handlers */
	var input_rollovers = $$('input[type^="image"]');
	input_rollovers.each(function(el){
		var src = el.src;
		var tmp = src.split(".");
		var src_rollover = tmp.without(tmp[tmp.length-1]).join('.') + '_hover' + '.' + tmp[tmp.length-1];
		Event.observe($(el), "mouseover", function(e){
			Event.element(e).src = src_rollover;
		}.bind(this))
		Event.observe($(el), "mouseout", function(e){
			Event.element(e).src = src;
		}.bind(this))
	});
});

/* temp placeholder function to test car results click */
function ptfs(index) {
    index = index.strip();
	index += '&N=' + $F('N') + '&search=' + $F('search')+ '&D=' + $F('D') + '&zip=' + $F('zip');
	$('N').value = '';
	$('__EVENTTARGET').name = '__METOO';
	$('__EVENTARGUMENT').name = '__METHREE';
	$('__VIEWSTATE').name = '__IGNORE';
	document.forms[0].action = index;
	document.forms[0].submit();
}

/* Added by JN, modified by HP */
function login_widget(init){
	if (!$("mykmx_login")) return;
	if (init!==true) {
		$("mykmx_login").toggleClassName("hide");
	}
	var state = !($("mykmx_login").hasClassName("hide"));
	if ($("myCarMax_close")) $("myCarMax_close").style.display = (state) ? "block" : "none";
	if ($("myCarMax_login")) $("myCarMax_login").style.display = (state) ? "none" : "block";
	if ($("myCarMax_reg")) $("myCarMax_reg").className = (state) ? "last hilite" : "last";
	if ($("whats-this")) $("whats-this").childNodes[0].style.backgroundImage = (state) ? "url(../../img/common/header/ico_whats_this_2.gif)" : "url(../../img/common/header/ico_whats_this.gif)";
}

/* images for toggling hidden/displayed copy */
var openImg = new Image();
openImg.src = "../../img/community/icon_open.gif";
var closedImg = new Image();
closedImg.src = "../../img/community/icon_close.gif";

function processCompareTables(){

	/* locate required HTML elements */
	var container = $$("table.compare")[0];
	var tLeft  = $$('table.compare-leftnav')[0];
	var tRight = $$('table.compare-rightnav')[0];
	var scrollContainer = $$('div.scroll-container')[0];
	var simulators = $$('div.scroll-simulator');

	/* If not found, script fails, exit */
	if (typeof container == "undefined" || typeof tLeft == "undefined" || typeof tRight == "undefined" || typeof scrollContainer == "undefined" || typeof simulators == "undefined") return;

	/* Tweak Safari rendering issues */
	if (isSafari) {
		$(container).style.marginTop = "-20px";
		simulators[0].style.height = "21px";
		simulators[1].style.height = "auto";
	}

	/* resize hidden image to display upper scroll bar identically with lower scroll bar */
	var img = simulators[1].getElementsByTagName('img')[0];
	img.style.width = parseInt(tRight.scrollWidth, 10) + "px";

	/* process rows of both tables */
	lRows = $A(tLeft.getElementsByTagName('tr'));
	rRows = $A(tRight.getElementsByTagName('tr'));
	for (var i = 0; i < lRows.length; i++) {

		/* All other browsers respect setting row height; Safari requires setting cell height */
		var lRow = lRows[i]
		var rRow = rRows[i];
		var lCell = lRow.getElementsByTagName('td')[0];
		var rCell = rRow.getElementsByTagName('td')[0];
		var lHeight = lCell.offsetHeight;
		var rHeight = rCell.offsetHeight;

		/* Based on general content, assume right row is taller */
		var changeValue = rHeight;
		/* Insert offset for IE; doesn't include padding in calculation? */
		var offset = (Prototype.Browser.IE) ? 20 : 0;

		if (lHeight !== rHeight) {
			if (lHeight >= rHeight) {
				changeValue = lHeight
			}
			lCell.style.height = rCell.style.height = changeValue - offset + "px";
		}

	}

	/* Event handler for top scroll bar */
	Event.observe($(simulators[1]), 'scroll', function(e){
		var el = Event.element(e);
		if ($(scrollContainer).scrollLeft != el.scrollLeft) {
			$(scrollContainer).scrollLeft = el.scrollLeft;
		}
	}.bindAsEventListener(this));

	/* Event handler for bottom scroll bar */
	Event.observe($(scrollContainer), 'scroll', function(e){
		var el = Event.element(e);
		if ($(simulators[1]).scrollLeft != el.scrollLeft) {
			$(simulators[1]).scrollLeft = el.scrollLeft;
		}
	}.bindAsEventListener(this));

	var resultsReturn = $$('li.notes a')[0];
	if(resultsReturn)
	{
	    Event.observe(resultsReturn, 'click', function(el){
	        Event.stop(el);
	        $('__VIEWSTATE').name = $('__EVENTARGUMENT').name = $('__EVENTTARGET').name = 'IGNORE';
	        document.forms[0].action = resultsReturn;
	        document.forms[0].submit();
	    });
	}

	var carLink = $$('td a[rel]');
	if(carLink)
	{
    	carLink.each(function(el){
    	if (el.getAttribute('rel') != "popup") {
		Event.observe(el, 'click', function(e){
			Event.stop(e);
			document.forms[0].action = el.getAttribute('href') + '?' + el.getAttribute('rel');
			document.forms[0].submit();
		});
		}
	});
	}

}

/* Function to redirect from a select box change. */
function selectRedirect(selectBox)
{
	destination = selectBox.options[selectBox.selectedIndex].value;
	if (destination) location.href = destination;
}

function toggleFilter(changed)
{
    filtersChanged = changed;
}

function buildFilterString()
{
    var priceQs = "sP";
    var mileageQs = "sM";
    var yearQs = "sY";
    
    var priceMin = $F('priceL');
    if(priceMin==0)
        priceMin='NA';
    var priceMax = $F('priceR');
    if(priceMax==0)
        priceMax='NA';
        
    var mileageMin = $F('mileageL');
    if(mileageMin==0)
        mileageMin='NA';
    
    var mileageMax = $F('mileageR');
    if(mileageMax==0)
        mileageMax='NA';
        
    var yearMin = $F('yearL');
    if(yearMin==0)
        yearMin='NA';
        
    var yearMax = $F('yearR');
    if(yearMax==0)
        mileageMax='NA';
    
    var pattern = '&' + priceQs + '=' + priceMin + ' ' + priceMax + '&' + mileageQs + '=' + mileageMin + ' ' + mileageMax + '&' + yearQs + '=' + yearMin + ' ' + yearMax;
    return pattern;
}

function resetDropDowns(rsVal)
{
    var rsVals = rsVal.split(',');
    for(var i = 0; i < rsVals.length; i++)
    {
        var rs = rsVals[i].split('=');
        if(rs[0] == "sP")
        {    
            var vals = rs[1].split(' ');
            setDdlVal('priceL',vals[0]);
            setDdlVal('priceR',vals[1]);
        }
        if(rs[0] == "sM")
        {
            var vals = rs[1].split(' ');
            setDdlVal('mileageL',vals[0]);
            setDdlVal('mileageR',vals[1]);
        }
        if(rs[0] == "sY")
        {
            var vals = rs[1].split(' ');
            setDdlVal('yearL',vals[0]);
            setDdlVal('yearR',vals[1]);
        }      
    }
}

function setDdlVal(element, value)
{
    var el = $(element);
    if(el)
    {
        if(el.options)
        {
            var isSet = false;
            for(var i = 0; i < el.options.length && !isSet; i++)
            {
                if(el.options[i].value == value)
                {
                    el.selectedIndex = i;
                    isSet = true;
                }
            }
        }
    }
}
/* Search Stuff - to be moved to a search.js */
function gs(page, action) {
    var link='';
    if(page.length > 0)
        link = page;
    link += '?' + action;
    if($F('search_state').length > 0)
        link += '&' + $F('search_state');
    location.href = link;
}
