// JavaScript Document


$(document).ready(init);
function init()
{
	dropdownMenu();
	if ($("div.quote").get(0)) home_page_quotes();
	//if ($("div.collapsed_box").get(0)) collapse_boxes();
	if ($("#convertor1").get(0)) convert1_init();
	//if ($("#map_canvas").get(0)) map_locator();
	
	
	if ($("#accept_btn").get(0)) check_accept();
	
}



function dropdownMenu(){
		var i=0;
		$("#nav").find("ul").each(
				function()		
					{
						var li = $(this.parentNode).find("span").get(0);
						var ul = this;
						i++; ul.i = i;
						li.ch = this;
						
						ul.hideBox = function () {
							$(this).slideUp(200); 	
							//$(this).css("display", "none");
						} 
						ul.showBox = function () {
							$(this).slideDown(200); 
							//$(this).css("display", "block");	
						} 
						
						$(li).mouseover(
								function () {
									var ul = this.ch;
									window.clearTimeout(ul.tm);
									ul.showBox();
								}
						)//mouseover
						
						$(li).mouseout(
								function () {
									var ul = this.ch;
									window['obj'+ul.i] = ul;
									ul.tm = window.setTimeout("this['obj"+ul.i+"'].hideBox()",200);
								}
						)//mouseout
						
						$(ul).mouseover(
							function () {
								window.clearTimeout(this.tm);
							}
						)//mouseover
						
						$(ul).mouseout(
								function () {
									var ul = this;
									window['obj'+ul.i] = ul;
									ul.tm = window.setTimeout("this['obj"+ul.i+"'].hideBox()",200);
								}
						)//mouseout
					}
		)//each
	}

/*function convert1_init(form) {
	var arr = new Array();
	
	//depends on mm
	arr.push(new Array('Millimeters', 1));
	arr.push(new Array('Centimeters', 10));
	arr.push(new Array('Meter', 1000));
	arr.push(new Array('Kilometers', 100000));
	arr.push(new Array('Miles', 1609344));
	arr.push(new Array('Inches', 25.4));
	arr.push(new Array('Feet', 304.8));
	arr.push(new Array('Yards', 914.4));
	
	
	
	$("#convertor1 > input:button").click(function(){
			var x = $("#convertor1 > input:text").get(0).value;
			var s = $("#convertor1 > select").get(0).value;
			
			var reg = /\b(\d+)\b/;
			var result=reg.test(x); 
			
			if (!result) {
					alert('Only numbers are accepted');
					return;
				}
			
			
			var ind = -1;
			for (var i=0; i<arr.length; i++)  {
				if (s==arr[i][0]) 
					{
						ind = i;
						i = arr.length;
					}
			}
			if (ind!=-1) {
				var koef = x*arr[ind][1];
				var str_th = '';
				var str_td = '';
				for (var i=0; i<arr.length; i++) {
					if (s!=arr[i][0]) {
						str_th += '<th>'+arr[i][0]+'</th>';
						str_td += '<td>'+Math.round((koef/arr[i][1])*100000)/100000+'</td>';
					}
				}
				$("#convertor1 > div").get(0).innerHTML = '<p class="header2"><strong>Results</strong></p><table class="results"><tr>'+str_th+'</tr><tr>'+str_td+'</tr></table>';	
			}
    })
}*/


function convert1_init(form) {
	var arr = new Array();
	
	//depends on mm
	arr.push(new Array('Millimeters', 1));
	arr.push(new Array('Centimeters', 1/10)); //1 mm = 1/10cm
	arr.push(new Array('Meters', 1/1000)); //1mm = 1000m
	arr.push(new Array('Kilometers', 1/1000000)); 
	arr.push(new Array('Miles', 1/1609344));
	arr.push(new Array('Inches', 1/25.4));
	arr.push(new Array('Feet', 1/304.8));
	arr.push(new Array('Yards', 1/914.4));
	
	/*$('#convertor1 > input:text').keyup(function(event){
    	//alert(event.keyCode);
		var str = this.value;
		if (event.keyCode < 48 || event.keyCode > 57){
  				 void(0);
				//this.value = str.substr(0, str.length-1);
 		}
	});*/

	
	$("#convertor1 > input:button").click(function(){
			var x = $("#convertor1 > input:text").get(0).value;
			var s = $("#convertor1 > select").get(0).value;
			
			var reg = /\b(\d+)\b/;
			var result=reg.test(x); 
			
			if (!result) {
					alert('Only numbers are accepted');
					return;
				}
			
			
			var ind = -1;
			for (var i=0; i<arr.length; i++)  {
				if (s==arr[i][0]) 
					{
						ind = i;
						i = arr.length;
					}
			}
			if (ind!=-1) {
				var koef = x/arr[ind][1]; //amound kg
				var str_th = '';
				var str_td = '';
				for (var i=0; i<arr.length; i++) {
					if (s!=arr[i][0]) {
						str_th += "<th>"+arr[i][0]+"</th>";
						var _temp = Math.round((koef*arr[i][1])*1000000)/1000000;
						str_td += "<td>"+_temp+"</td>";
					}
				}
				$("#convertor1 > div").get(0).innerHTML = '<p class="header2"><strong>Results</strong></p><table class="results"><tr>'+str_th+'</tr><tr>'+str_td+'</tr></table>';	
			}
    })
}

var map;
var directionsPanel;
var point = new Object;

function map_locator(){
		map = new GMap2(document.getElementById("map_canvas"));
		directionsPanel = document.getElementById("route");
		
		map.addControl(new GSmallMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
	
	
}


function handleErrors(){
                          
						   /*if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
                             alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
                           else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
                             alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
                           
                           else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
                             alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

                        //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
                        //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
                           else if (gdir.getStatus().code == G_GEO_BAD_KEY)
                             alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

                           else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
                             alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
                           else alert("An unknown error occurred.");*/
                        }

var lat;
var lng;
var div;
function CGCallback(responce) {
	
    if (responce.Status.code != 200) {
		if (responce.Status.code == G_GEO_UNKNOWN_ADDRESS)
                             alert("Google Map Error:\nNo corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + responce.Status.code);
							 else  alert("Google Map Error:\nError code: " + responce.Status.code);
     // alert(responce.Status.code);
      
	  $("#map_canvas").hide();
	  return;
    }

	$("#map_canvas").show();
	lat = responce.Placemark[0].Point.coordinates[1];
    lng = responce.Placemark[0].Point.coordinates[0];
	
		
	map.setCenter(new GLatLng(lat, lng), 12);
	
	
	
	var market = new GMarker(new GLatLng(lat, lng));
	GEvent.addListener(market, 'click', function() {market.openInfoWindowHtml(div); });
	
	//GEvent.addListener(market, 'mouseover', function() {market.openInfoWindowHtml(div); });
	//GEvent.addListener(market, 'mouseout', function() { market.closeInfoWindow(); });
	map.addOverlay(market);
	market.openInfoWindowHtml(div);
  }


function updatemap(title, address, city, country, prov, pcode){
	
	div = "<div class='descr'><h3>"+title+"</h3><p>"+address+'<br />'+city+', '+prov+'<br /> '+country+"</p></div>";
	var cg;
	cg = new GClientGeocoder();
	//alert(address+' '+city+' '+prov+' '+country+' '+pcode);
	cg.getLocations(address+' '+city+' '+prov+' '+country+' '+pcode, CGCallback);
}

function check_address(){
	var title = document.forms[0].branch_title.value;
	var address = document.forms[0].branch_address.value;
	var city = document.forms[0].branch_city.value;
	var prov_id = document.forms[0].id_province.value;
	var prov='';
	
	$("option").each(
	  function()
	  {
		if (this.value==prov_id)  prov = this.innerHTML;
	  }
	);
	var country = document.forms[0].param1.value;
	if ((address == '')||(city=='')) alert('Please enter the address.');
	else
	updatemap(title, address, city, country, prov);
}





var date = new Date();
  	date.setMonth(date.getYear()+30);
  
var param2 = "expires=" + date.toUTCString()+"; path=/";


function set_favorite_branch(id) {
	var cookie_string = "winroc_favorite_branch=" + escape ( id )+ "; winroc_favorite=true; "+param2;
 	document.cookie = cookie_string;
	
}

function set_favorite_branch2(id) {
	var cookie_string = "winroc_favorite_branch=" + escape ( id )+ "; winroc_favorite=false; "+param2;
 	document.cookie = cookie_string;
}

function set_favorite_branch_alt(id) {
	if (get_cookie("winroc_favorite")=='false') 
		{
			set_favorite_branch2(id);
		}
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if ( results ) {
    return (  unescape ( results[2] ) );
  }
  else
    return false;
}


function home_page_quotes(){
	var ind =Math.floor(Math.random()*2)+1;
	$("div.mainContainer-st02").css("background", "transparent url(_img/home-pic/"+ind+".jpg) no-repeat scroll -20px bottom");	
	$("div.quote").css("display","none")
	$($("div.quote").get(ind-1)).css("display","block")
}


function check_accept(){
    $("#accept_btn").click(
			function () {
				if ($("#agreebox").get(0).checked) 
					{
						$("#form1").get(0).submit();
					}
				else 
					alert("Check the box if you accept the terms above.");
			}
	)
}

function collapse_boxes(){
	
	$("div.collapsed_box").each(
				function()		
					{
					
					
						/*var h4 = $(this).find("h4").get(0);
						h4.box = $($(this).find("table").get(0));
						
						if (this.className=='collapsed_box collapsed_box_expanded')
							h4.boxState = 'collapse'; 
						else
							h4.boxState = 'expand'; 
						
						$(h4).click(
								function () {
									
									if (this.boxState=='collapse') {
										this.box.slideUp(200);
										
										$($(this).find("img").get(0)).attr("src", "../../_img/+.gif");
										//$($(this).find("img").get(0)).attr("alt", "expand the box");
										
										
										//this.box.css("display", "block");
										this.boxState='expand';
									} else 
									if (this.boxState=='expand') {
										this.box.slideDown(200);
										$($(this).find("img").get(0)).attr("src", "../../_img/-.gif");
										//$(this.find("img").get(0)).attr("alt", "collapse the box");
										//this.box.css("display", "none");
										
										this.boxState='collapse';
									}
									
								}
						);*/
						
						
					/*
						h4.box = $(this.parentNode).find("table").get(0);
						this.boxState = 'collapsed';
						
						box.hideBox = function () {
							$(this).slideUp(200); 	
							//$(this).css("display", "none");
						} 
						box.showBox = function () {
							$(this).slideDown(200); 
							//$(this).css("display", "block");	
						} 
						
						this.mouseover(
								function () {
									alert(this.boxState);
									if (this.boxState=='collapsed') {
										this.box.showBox();
										this.boxState=='expanded';
									} else 
									if (this.boxState=='expanded') {
										this.box.hideBox();
										this.boxState=='collapsed';
									}
								}
						)//click*/
						
						
					} //function
		) //each
}