/*global alert, $, concat */

var website = {};
var values = [], formdata = [], loadPage = 'load', currPage = false;

website.emailChecked = false;
website.sname	     = false;
website.modcount     = 0;
website.modid	     = false;
website.make	     = false;
website.model	     = false;
website.stocknum     = false;

function checkEmail(email) {
	
	var purl, self = this;
	this.result = false;

	function confirmEmail(val){
		self.result = val;
		website.emailChecked = self.result;
	}

	purl = "scripts/ajax.php?action=checkemail&email="+email+"&sid="+Math.random();
	$.ajax({ url: purl, success: function(html) { if(html === "false") { alert("Invalid Email Address Entered!"); } else { confirmEmail(true); } } });// alert("result = "+emailCheck);

//	website.emailChecked = this.result;
	return this.result;

}

function subscribeNewsletter() {
	var name, email, purl;

	name = $('#name').val();
	email = $('#email').val();

	if (website.emailChecked !== false) { // alert("web thingy = "+website.emailChecked);
		purl = "scripts/ajax.php?action=newssub&name="+name+"&email="+email+"&sid="+Math.random();
	} else {
	//	alert("failing!");
		return false;
	}

	purl = encodeURI(purl);

	$('#newsletter').load( purl );

	/* $.ajax({ url: purl, success: function(html) { $("#newssubres").append(html); } }); */
}

function checkNewsSub() {
	var name, email, chk;
	name = $('#name').val();
	email = $('#email').val();

	chk = checkEmail(email);
	setTimeout(function(){ if(chk === false && website.emailChecked === false) { return false; } if(name && email){ subscribeNewsletter(); } else { alert("Please complete both fields first..."); return false; }}, 500);
}

function contactExpressway() {
	var name, email, phone, message, purl;

	name = $('#contactname').val();
	email = $('#contactemail').val();
	phone = $('#contactphone').val();
	message = $('#contactmessage').val();

	if(message === '') { message = "No message was submitted."; }

	message = message.replace(/,/g, '');

/*	purl = "scripts/ajax.php?action=contactus&name="+name+"&email="+email+"&phone="+phone+"&message="+message+"&sid="+Math.random();
	purl = encodeURI(purl);

	$('#contactform').load( purl ); */

	$.post("scripts/ajax.php?action=contactus", { name: name, email: email, phone: phone, message: message}, function(data) { $('#contactform').html(data); });

}

function contactCheck() {

	var name, email, phone, purl, tested = false;

	name = $('#contactname').val();
	email = $('#contactemail').val();
	phone = $('#contactphone').val();

	tested = checkEmail(email); // alert(tested); alert(website.emailChecked);
	
	setTimeout(function(){	if (tested === false && website.emailChecked === false) { return false; } if (!isFinite(phone)) { alert("Please enter a valid phone number"); return false; } }, 600);

	setTimeout(function(){ if(name !== '' && email !== '' && phone !== '' && isFinite(phone) && (tested === true || website.emailChecked === true)){
					contactExpressway();
				}
				else {
					alert("Please complete all required fields before submitting");
					return false;
				}
	}, 1200);
}

function galleryChanger(gallery, elm) {
	
	var purl;
	purl = "scripts/ajax.php?action=gallerychange&gallery="+gallery+"&sid="+Math.random();

	$('#workBox').load( purl );

	function reset(){
		if ($('#photos')) {
			$(document).ready(function(){
				$('#photos').galleryView({
					panel_width: 620,
					panel_height: 329,
					frame_width: 69,
					frame_height: 69
				});
			});
		} else {
			setTimeout( function(){ reset(); }, 100);
		}
	}
	if (elm) { // alert("is elm!");
		setTimeout( function(){ reset(); }, 1000);
	}
	
	/* Using HTML DOM to change class of clicked <li> */
	if (elm) {
		$("li").removeClass("subBntCurrent").addClass("subBnt");
		elm.parentNode.className='subBnt subBntCurrent';
	}

	/* move page up to view gallery */
	setTimeout(function() { document.location.hash = 'work'; }, 1100);
}

function getProduct(pid, val, lid) {

	var purl;
	$('#servicesBoxRight').html('<p><img style="border:0;" alt="Loading - please wait" src="../images/loading.gif" /> One moment please - fetching data...</p>');
	if(val === 's') {
		pid = "ser-"+pid;
	} else {
		pid = "pro-"+pid;
	}
	purl = "scripts/ajax.php?action=getproduct&pid="+pid+"&sid="+Math.random();

	document.location.hash = 'viewup';
	$('#servicesBoxRight').load( purl );
	setTimeout(function(){ document.location.hash = 'viewup'; }, 100);
	$("li").removeClass("current");
	lid.parentNode.className = 'current';
	
}

function getGets(sString, find) {
	var name, gvalue, vPair, i, sPairs; 
	sString=sString.substring(1); sPairs=sString.split("&");
    //	alert(sString);
	if(sPairs.length===1){
		sPairs=sString; vPair=sPairs.split("="); name=vPair[0]; gvalue=vPair[1];
		if(name===find){ return gvalue; } else { return "0"; }
	} else {
    //	    alert(sPairs.length);
		for(i=0;i<=sPairs.length;i++) {
			/* iterate */	// alert(sPairs);
			sPair = sPairs[i];
			vPair=sPair.split("=");
			name=vPair[0]; gvalue=vPair[1];
			if(name===find){ return gvalue; }
		}
		return '0';
	}
}

function getSeries(mid) {
    var req, purl, value;
    purl = "/scripts/ajax.php?action=getSeries&mid="+mid+"&sid="+Math.random();

    $('#showseries').load( purl );
    $('#showmodels').html('');

    value = formdata[mid];
  //  alert(value);
    $('#prodformbox').html(value);
}

function getModels(serid) {
    var req, purl;

    purl = "/scripts/ajax.php?action=getModels&sed="+serid+"&sid="+Math.random();

    $('#showmodels').load( purl );
}

function getSerieName(sid) {
    var req, purl, self = this;

    purl = "/scripts/ajax.php?action=getSerieName&sed="+sid+"&sid="+Math.random();

    $.ajax({ url: purl, success: function(html) { website.sname = html; } });

    setTimeout(function() { return; }, 1200);
}

function getModCount(pathway, sid) {
    var purl, self = this;

    purl = "/scripts/ajax.php?action=getModCount&pathway="+pathway+"&sed="+sid+"&sid="+Math.random();

    $.ajax({ url: purl, success: function(html) { website.modcount = html; } });
 //   alert("modcount = "+website.modcount);
    setTimeout(function() { return; }, 1200);
}

function getModId(pathway, sid) {
    var purl;

    purl = "/scripts/ajax.php?action=getModId&pathway="+pathway+"&sed="+sid+"&sid="+Math.random();

    $.ajax({ url: purl, success: function(html) { website.modid = html; } });
 //   alert("modid = "+website.modid);
    setTimeout(function() { return; }, 1200);
}

function getProdModels(serid, pathway) {    // alert(serid);
    var req, purl, sername, modcount, purl1, prurl2;

    website.sname = false;

    getSerieName(serid);
    getModCount(pathway, serid);
    getModId(pathway, serid);

 //   sername = website.result;

 //   if(!sername || sername == '') {
 //    sername = website.result;
 //   }
 
 //   alert("sername = "+ sername);
 //   alert("result = "+ website.result); 

    setTimeout(function() {
	if(website.sname) {

	    $('#seriesTitle').html("<h2>Series:<br /> "+website.sname+"</h2>");
	    $('#prodimg').attr('src', 'images/'+pathway+'/products/'+website.sname.toLowerCase()+'.jpg');

	//    getModCount(pathway, serid);
	//    getModId(pathway, serid);
	    website.pcount = website.modcount;

	    if(website.modcount <= 0) { getModCount(pathway, serid); }
	    if(website.modid === false) { getModId(pathway, serid); }

	    req = '<a href="#" onclick="return false;"><img src="images/controller-prev.jpg" alt="prev" /></a>  1 / '+website.modcount+'  <a href="#" onclick="showProduct(\''+pathway+'\', \''+website.modid+'\', \''+serid+'\'); return false;"><img src="images/controller-next.jpg" alt="next" /></a>';
	    $('#boxPag').html(req);
	}

	purl = "/scripts/ajax.php?action=getProdModels&sed="+serid+"&pway="+pathway+"&sid="+Math.random();
	purl1 = "/scripts/ajax.php?action=getFirst&sed="+serid+"&pway="+pathway+"&sid="+Math.random();
	
	$('#modMenu').load( purl );
	$('#prodImage').load( purl1 );
	
	}, 2500);
}
function specialProdCheck(v) {
    var make, model;
    make    = $('#make').val();
    model   = $('#model').val();

    if(make && model) {
	return true;
    }
    else {
	alert("Minimum selection must include Make and Model. Thank You...");
	return false;
    }
}
function prodCheck(v) {
    var make, serie, model;
    make    = $('#make').val();
    if(v == "defer") {
	serie = "na";
    } else {
	serie   = $('#series').val();
    }
    model   = $('#model').val();

    if(make && serie && model) {
	return true;
    }
    else {
	alert("Minimum selection must include Make, Series and Model. Thank You...");
	return false;
    }
}

function showProduct(pathway, mid, sid, pos) {
    var req, purl, tcnt;

    tcnt = $('#modcount').val();
    
 //   alert("pos = "+ pos);
 //   alert("tcnt = "+ tcnt);    

    if(pos <= 0) { return false; }
  //  if(tcnt >= pos) { alert("returning!"); return false; } // else { alert("Oppsing!"); return; }
    if(tcnt - pos <= 0) { return false; }
	
    purl = "/scripts/ajax.php?action=showProduct&pway="+pathway+"&sed="+sid+"&mid="+mid+"&tcnt="+tcnt+"&sid="+Math.random();

    $('#prodImage').load( purl );
}

function getClearance(val, that, pathway) {
    $('.clrlink').removeClass('subNavCurrent');
//    $('#'+that).addClass('subNavCurrent');
    var purl, action;

    if(pathway == "floor_stock") { action = "getFloorstock"; } else { action = "getClearance"; }

    val = encodeURI(val); // .replace(" ", "%20");
    purl = "/scripts/ajax.php?action="+action+"&make="+val+"&sid="+Math.random();

    $('#bigBox').load( purl );
 //   val = val.replace(" ", "_");
    val = decodeURI(val); // .replace("%20", " ");
    $('#clrheading').html( val );    
}

function sendEnquiry( make, model, stocknum) {
    if(make && model && stocknum) {
	document.location="/contact_us?make="+make+"&model="+model+"&stocknum="+stocknum+"&sid="+Math.random();
    }
}

website.make = getGets(location.search, 'make');
website.model = getGets(location.search, 'model');
website.stocknum = getGets(location.search, 'stocknum');

function setFormValues() {
    var html = '';
    $('#enq_make').val( website.make );
    $('#enq_model').val( website.model );
    $('#enq_stocknum').val( website.stocknum );

    if(website.make && website.make != 0) html += "Make: " + decodeURI(website.make)+" ";
    if(website.model && website.model != 0) html += "\nModel: " + decodeURI(website.model)+" ";
    if(website.stocknum && website.stocknum != 0) html += "\nStockNumber: " + website.stocknum;

    $('#emailm').val( html ); // "Make: " + website.make.replace('%20', ' ') + "\n" + "Model: " + website.model.replace('%20', ' ') + "\n" + "StockNumber: " + website.stocknum );
}

function setActiveLink(make) {
    var links = {'Hino':'clrlink1', 'MAN':'clrlink2', 'Case':'clrlink4', 'Western Star':'clrlink3'};
    $('.clrlink').removeClass( 'subNavCurrent' );
    $('#'+links[make]).addClass( 'subNavCurrent' );
}

