var _partenerId = "";
var _nextFunctions = [''];
var _flash = getMovieName("quickQuote");
var _insQ = new insQ();	
var _Q = new Object();
var _debug = false;
var _showBanner = true;

/*
QuoteObject:

  QfirstLoad
  Qzip                     the zip in the text box
  Qstate                the state for the zip  (blank if not found)
  Qage                   the age currently selected
  QageList             the list of ages
  Qgender            the gender currently selected
  QgenderList     the list of gender
  QmaritialStatus               the currently selected maritial status
  QmaritialStatusList        the list of all maritial status
  Qyear                  the year currently selected
  QyearList           the list of all years
  Qmake               the make currently selected
  QmakeList         the list of makes
  Qmodel              the model currently selected
  QmodelList       the list of all models
  QcurrentField                  the fromField used to in the SetFromFlash call
  QcurrentFieldValue      the fromValue used to in the setFromFlash call
  QerrorCode      the error code that HTML send to flash
  QerrorMessage              the error message that HTML send to flash
  QminPre            min. premium
  QmaxPre           max. premium
  QavgPre             average premium
  QmedPre	      mediam premium
  QgoButton		if the go button visible.
  QGelSelected	if a Gel is clicked.
  QGelSelectedNum  which Gel is clicked.

The function name flash calls HTML: setFromFlash(quoteObject)
The function name HTML calls flash: callPlayBall(quoteObject)

*/

//window.onload = function()
function checkFlash()
{
	
	flashLoaded = true;
	_flash = getMovieName("quickQuote");
	initQ();
	
	
        if (window.location.href.indexOf('www-dev') > 0)
	{
    	    _insQ = new insQ("http://www-dev.corp.insweb.net/tools/inswebquad/insQ.ashx");
        }
        else if (window.location.href.indexOf('www-qa') > 0)
        {
            _insQ = new insQ("http://www-qa.corp.insweb.net/tools/inswebquad/insQ.ashx");
        }
        else if (window.location.href.indexOf('www.insweb.com') > 0)
        {
            _insQ = new insQ("http://www.insweb.com/tools/inswebquad/insQ.ashx");
        }
    
    
	var zip = gup('zip_code');
	_Q.Qzip = zip;
    	_Q.Qstate = findState(zip);
    	_nextFunctions = ['callPlayBall'];
	
	if (_Q.Qstate == "")
	{
	   _Q.Qstate = 'CA';
	   _Q.QerrorCode = 0;
	}
	else
	{
		_nextFunctions.push('getYear');
	}
	
	_partenerId = gup('id');
	if (_showBanner == true)
		window.setTimeout("refreshBanner()",3000);
	//alert(dumpQ());
	
	callNextFunction();
	
	_Q.QfirstLoad = true;
	_flash.callPlayBall(_Q);
	
	
}
function initQ()
{
  _Q.QfirstLoad;
  _Q.Qzip = "";
  _Q.Qstate = "";
  _Q.Qage = "";
  _Q.QageList = ['','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59','60','61','62','63','64','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80'];
  _Q.Qgender = "";
  _Q.QgenderList = ['','Male','Female'];
  _Q.QmaritialStatus = "";
  _Q.QmaritialStatusList = ['','Single','Married','Divorced','Widowed'];
  _Q.Qyear = "";
  _Q.QyearList = ['']; //['','2008','2007','2006','2005','2004','2003','2002','2001','2000','1999','1998','1997','1996','1995','1994','1993','1992','1991','1990','1989','1988','1987','1986','1985','1984','1983','1982','1981'];
  _Q.Qmake = "";
  _Q.QmakeList = [''];
  _Q.Qmodel = "";
  _Q.QmodelList = [''];
  _Q.QcurrentField = "";
  _Q.QcurrentFieldValue = "";
  _Q.QerrorCode = 0;
  _Q.QerrorMessage = "";
  _Q.QminPre = 0;
  _Q.QmaxPre = 0;
  _Q.QavgPre = 0;
  _Q.QmedPre = 0;
  _Q.QgoButton = 1;
  _Q.QGelSelected = false;
  _Q.QGelSelectedNum = 0;
}
function dumpQ()
{
    var s = "";
    s = s+ "Qzip = " + _Q.Qzip + "\n";
    s = s+ "Qstate = " + _Q.Qstate + "\n";
    s = s+ "Qage = " + _Q.Qage + "\n";
    s = s+ "QageList = " + _Q.QageList + "\n";
    s = s+ "Qgender = " + _Q.Qgender + "\n";
    s = s+ "QgenderList = " + _Q.QgenderList + "\n";
    s = s+ "QQmaritialStatusip = " + _Q.QmaritialStatus + "\n";
    s = s+ "QmaritialStatusList = " + _Q.QmaritialStatusList + "\n";
    s = s+ "Qyear = " + _Q.Qyear + "\n";
    s = s+ "QyearList = " + _Q.QyearList + "\n";
    s = s+ "Qmake = " + _Q.Qmake + "\n";
    s = s+ "QmakeList = " + _Q.QmakeList + "\n";
    s = s+ "Qmodel = " + _Q.Qmodel + "\n";
    s = s+ "QmodelList = " + _Q.QmodelList + "\n";
    s = s+ "QcurrentField = " + _Q.QcurrentField + "\n";
    s = s+ "QcurrentFieldValue = " + _Q.QcurrentFieldValue + "\n";
    s = s+ "QerrorCode = " + _Q.QerrorCode + "\n";
    s = s+ "QerrorMessage = " + _Q.QerrorMessage + "\n";
    s = s+ "QminPre = " + _Q.QminPre + "\n";
    s = s+ "QmaxPre = " + _Q.QmaxPre + "\n";
    s = s+ "QavgPre = " + _Q.QavgPre + "\n";
    s = s+ "QmedPre = " + _Q.QmedPre + "\n";
    s = s+ "QgoButton = " + _Q.QgoButton + "\n";
    s = s+ "QGelSelected = " + _Q.QGelSelected + "\n";
    s = s+ "QGelSelectedNum = " + _Q.QGelSelectedNum + "\n";
    return s;
}
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
  	return "";
  else
    return results[1];
}

function firstGel(zip)
{
	debug(zip + ' in firstGel');
    var url = "/cgi-bin/auto.exe?";
    if (zip)
     	url = url + "GarageZip=" + zip + "&";
    if (_partenerId != '')
    	url = url + "id=" + _partenerId + "&";
    window.open(url);	
}

var getURLValue;

// gets the url string
function getURLstring(){
	if (window.location.href.indexOf('www-dev') > 0)
   	 {
                getURLValue = "&var1=DEV.QQT";
    	}
    	else if (window.location.href.indexOf('www-qa') > 0)
    	{
                getURLValue = "&var1=QA.QQT";
    	}
    	else if (window.location.href.indexOf('www.insweb.com') > 0)
    	{
                getURLValue = "&var1=PROD.QQT";
    	}
}


function secondGel(zip)
{
    getURLstring();
	var url = "ir_surehits_landing-stripdown.html?GarageZip=" + zip + "&statecode=" + _Q.Qstate;	
    	if (window.location.href.indexOf('www-dev') > 0 || window.location.href.indexOf('www-qa') > 0 || window.location.href.indexOf('www.insweb.com') > 0)
    	url = url + getURLValue;
    	window.open(url);	
}

function thirdGel(zip)
{
    var url = "/cgi-bin2/agentdirectory.exe?";
    if (zip)
     	url = url + "GarageZip=" + zip + "&GZip=" + zip + "&zip=" + zip + "&Landingpage=y&";
    if (_partenerId != '')
    	url = url + "id=" + _partenerId + "&";
    window.open(url);	
}

function getMovieName(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
	    return window[movieName]
	}
	else {
	     return document[movieName]
	}
}
function movieIsLoaded (theMovie) {
	if (typeof(theMovie) != "undefined") {
	  return theMovie.PercentLoaded() == 100;
	} else {
	  return false;
	}
}
function debug(message)
{
    if (_debug) alert(message);
}
function getRate()
{

	debug('in getRate\n' + dumpQ());

	var licenseyears = _Q.Qage - 16;
	var licenseyears1=  licenseyears +"y00m";
	var objJSON = {
	"License_State" : _Q.Qstate,
	"Model_Year_Y2K"  : _Q.Qyear,
	"Make"  : _Q.Qmake,
	"Model" : _Q.Qmodel,
	"Age"   : _Q.Qage,
	"Zipcode" : _Q.Qzip,
	"Status"	: _Q.QmaritialStatus,
	"Sex"   : _Q.Qgender,
	"US_License" : licenseyears1,
	"CA_License" : licenseyears1,
	"Verifiable_License" : licenseyears1,
	"Continuous_License" : licenseyears1,
	"Use" : "Work",
	"Annual" :"12,000",
	"Liability" : "100/300",
	"PD" : "50,000",
	"Comp" : "500",
	"Coll" : "500",
	"UMBI" : "100/300",
	"Med" : "5,000",
	"UMPD" : "3,500",
	"Rental" : "30",
	"Towing" : "50",
	"Term": "6",
	"Number_Drivers" : "1",
	"Number_Incidents" : "0",
	"Degree" : "Bachelors",
	"Credit_Tier" : "Good",
	"Payment_Type" : "Paid in Full",
	"Lapse" : ""
	};

	
  	var strJSON = JSON.stringify(objJSON);
	debug('strJSON\n' + strJSON);		
	
	_insQ.GetRates(strJSON,_Q.Qstate,populateQ_Rates);
	
} // getRate()

function getYear()
{
    debug('in getYear');
    _insQ.GetModelYear(_Q.Qstate,populateQ_Year);
}
function getMake()
{
    debug('in getMake');
    debug(dumpQ());
    _insQ.GetMakes(_Q.Qstate,_Q.Qyear,populateQ_Make);
}
function getModel()
{
    debug('in getModel');
    _insQ.GetModels(_Q.Qstate,_Q.Qyear,_Q.Qmake,populateQ_Model);
}
function populateQ_Year(response)
{
    debug('in populateQ_Year');
    var result = response.result;
    _Q.QyearList = [''];
    var found = false;
    if (result && result.length > 0)
    {
    	for (var i=0;i<result.length;i++)
    	{
    	  if (result[i].toString().indexOf('197') == -1 && result[i].toString() != '1980')
    	  {
      	      _Q.QyearList.push(result[i]);
      	      if (result[i] == _Q.Qyear)
      	        found = true;
      	  }
      	}
      	if (found == false)
      	  _Q.Qyear = '';
    }
    callNextFunction();
}
function populateQ_Make(response)
{
    debug('in populateQ_Make');
    var result = response.result;
    _Q.QmakeList = [''];
    if (result)
    {
    	for (var i=0;i<result.length;i++)
    	{
      	    _Q.QmakeList.push(result[i]);
      	}
    }
    callNextFunction();
}
function populateQ_Model(response)
{
    debug('in populateQ_Model');
    var result = response.result;
    _Q.QmodelList = [''];
    if (result)
    {
    	for (var i=0;i<result.length;i++)
      	    _Q.QmodelList.push(result[i]);
    }
    callNextFunction();
}
function compareNumber(a1,a2)
{
  if (parseFloat(a1) < parseFloat(a2))
  return -1;
  else
  return 1;
}
function populateQ_Rates(response)
{

    var result = response.result;
    if (result)
    {
	if (!result || result == '')
	{
	    _Q.QerrorCode = 11;
	    _Q.QerrorMessage = "Unable to get the quote this time. Please try again later.";
	    getMovieName("quickQuote").callPlayBall(_Q);
	    debug('populateQ_Rates: result is blank');
	    return;
	}
	var jsonArray = eval("(" + result + ")");
	if (!jsonArray.length)
	{
	    _Q.QerrorCode = 12;
	    _Q.QerrorMessage = "Unable to get the quote this time. Please try again later.";
	    getMovieName("quickQuote").callPlayBall(_Q);
	    debug('populateQ_Rates: jsonArray is empty');
	    return;
	}

	var count=0; 
	var prem= 0;
	var min = 99999999.0;
	var max = 0.0;
	var avg = 0.0;
	var avgFloat = 0.0;
	var total = 0.0;
	var arrPrem = new Array();
	for (var i=0;i<jsonArray.length-1;i++)
	{
	    if (jsonArray[i].Annual_Premium > 0)
	    {
	    	prem = parseFloat(jsonArray[i].Annual_Premium);
	    	total= parseFloat(total) + prem;
		if (prem > max) max = prem;
		if (prem < min) min = prem;
		arrPrem[count]=prem;
		count = count + 1;
		
	    	
	    } // if
	} // for
	avgFloat =Math.round(  ( total/count ) * 100 ) / 100;
	_Q.QminPre = parseInt(min);
	_Q.QmaxPre = parseInt(max);
	_Q.QavgPre = parseInt(avgFloat);
	arrPrem = arrPrem.sort(compareNumber);
	debug('Premiums:' + arrPrem);
	_Q.QmedPre = arrPrem[parseInt(arrPrem.length/2)];
	_Q.QerrorCode = 0;
	_Q.QerrorMessage = "";
	debug('populateQ_Rates dump\n' + dumpQ());
//alert(dumpQ());	
    } // if result
    else
    {
        _Q.QerrorCode = 11;
        _Q.QerrorMessage = "Unable to get the quote this time. Please try again later.";
        getMovieName("quickQuote").callPlayBall(_Q);
        debug('populateQ_Rates: result is blank');

        return;
    }
    callNextFunction();
}
function callNextFunction()
{

    debug('in callNextFunction: ' + _nextFunctions );
    if (_nextFunctions.length == 0) return;
    var nextFunction = _nextFunctions.pop();
    
     if (nextFunction == 'getRate')
    	getRate();
    else if (nextFunction == 'getYear')
    	getYear();
    else if (nextFunction == 'getMake')
    	getMake();
    else if (nextFunction == 'getModel')
    	getModel();
    else if (nextFunction == 'callPlayBall')
    {
		callPlayBall();
    }
    
}
var _flashLoaded = false;
function callPlayBall()
{
	try
	{
    	getMovieName("quickQuote");
		getMovieName("quickQuote").callPlayBall(_Q);
		_flashLoaded = true;
		//window.status += " " + _flashLoaded + " ";
	}
	catch (err) {
		_flashLoaded = false;
		//window.status += " " + _flashLoaded + " ";
		checkLoaded();
		
	}
}
function checkLoaded()
{
	if (_flashLoaded == false)
		window.setTimeout("callPlayBall()",1000);
}
function SetFromFlash(quoteObject)
{
    
    if (quoteObject.Qzip)
    {}
    else
    {
    	_Q.QerrorCode = 13;
    	_Q.QerrorMessage = "Unable to get the quote this time. Please try again later.";
    	getMovieName("quickQuote").callPlayBall(_Q);
    	return;
    }
    _Q = quoteObject;
    _Q.QminPre = 0;
    _Q.QmaxPre = 0;
    _Q.QavgPre = 0;
    _Q.QerrorMessage = "";
    _Q.QerrorCode = 0;
    
    debug('in SetFromFlash\n' + dumpQ());
    currentField = _Q.QcurrentField;
    isGoVisible = (_Q.QgoButton==1);

    if (_Q.QGelSelected == true)
    {
    	if (_Q.QGelSelectedNum == 1)
    	    firstGel(_Q.Qzip);
    	else if (_Q.QGelSelectedNum == 2)
    	    secondGel(_Q.Qzip);
    	else if (_Q.QGelSelectedNum == 3)
    	    thirdGel(_Q.Qzip);
    	_Q.QGelSelected = false;
    	return;
    }
    
    if (isGoVisible)
    {
	if(currentField == "submitBtn")
	{
	    _nextFunctions = ['callPlayBall'];
	    _nextFunctions.push('getRate');
		_nextFunctions.push('getYear');
	    callNextFunction();
	}
    	else if (currentField == 'zip')
    	{
    	    _Q.Qstate = findState(_Q.Qzip);
    	    //_Q.Qmake = "";
    	    _Q.QmakeList = [''];
    	    //_Q.Qmodel = "";
    	    _Q.QmodelList = [''];
    	    if (_Q.Qstate == '')
    	    {
    	      _Q.QerrorCode = 1;
    	      _Q.QerrorMessage = "Invalid zip code.";
    	    }
    	    _nextFunctions = ['callPlayBall'];
    	    if (_Q.Qmodel.length > 0)
    	      _nextFunctions.push('getModel');
    	    if (_Q.Qmake.length > 0)
    	      _nextFunctions.push('getMake');
    	    _nextFunctions.push('getYear');
    	    callNextFunction();
    	}
    	else if (currentField == 'age')
    	{
    	    getMovieName("quickQuote").callPlayBall(_Q);
    	}
    	else if (currentField == 'gender')
    	{
    		getMovieName("quickQuote").callPlayBall(_Q);
    	}
    	else if (currentField == 'married')
    	{
    		getMovieName("quickQuote").callPlayBall(_Q);
    	}
    	else if (currentField == 'year')
    	{
    	    //_Q.Qmake = "";
    	    _Q.QmakeList = [''];
    	    //_Q.Qmodel = "";
    	    _Q.QmodelList = [''];
    	    _nextFunctions = ['callPlayBall'];
    	    if (_Q.Qmodel.length > 0)
    	      _nextFunctions.push('getModel');
    	    _nextFunctions.push('getMake');
    	    callNextFunction();

    	}
    	else if (currentField == 'make')
    	{
    	    //_Q.Qmodel = "";
    	    _Q.QmodelList = [''];
	    _nextFunctions = ['callPlayBall'];
	    _nextFunctions.push('getModel');
	    callNextFunction();
    	}
    	else if (currentField == 'model')
    	{}
    }
    else
    {
    	if (currentField == 'zip')
    	{
    	    _Q.Qstate = findState(_Q.Qzip);
    	    if (_Q.Qstate == '')
    	    {
    	      _Q.QerrorCode = 1;
    	      _Q.QerrorMessage = "Invalid zip code.";
    	    }
       	    _nextFunctions = ['callPlayBall'];
  	    _nextFunctions.push('getRate');
    	    if (_Q.Qmodel.length > 0)
    	      _nextFunctions.push('getModel');
    	    if (_Q.Qmake.length > 0)
    	      _nextFunctions.push('getMake');
  	    _nextFunctions.push('getYear');
    	    //_Q.Qmake = "";
    	    //_Q.Qmodel = "";
    	    _Q.QmakeList = [''];
    	    _Q.QmodelList = [''];
    	    callNextFunction();

    	}
    	else if (currentField == 'age')
    	{
       	    _nextFunctions = ['callPlayBall'];
	  	    _nextFunctions.push('getRate');
  		    callNextFunction();
    	}
    	else if (currentField == 'gender')
    	{
       	    _nextFunctions = ['callPlayBall'];
	  	    _nextFunctions.push('getRate');
  		    callNextFunction();
    	}
    	else if (currentField == 'married')
    	{
       	    _nextFunctions = ['callPlayBall'];
	  	    _nextFunctions.push('getRate');
  		    callNextFunction();
    	}
    	else if (currentField == 'year')
    	{
    	    //_Q.Qmodel = "";
    	    _Q.QmodelList = [''];
    	    _nextFunctions = ['callPlayBall'];
	    _nextFunctions.push('getRate');
    	    if (_Q.Qmodel.length > 0)
    	      _nextFunctions.push('getModel');
	    _nextFunctions.push('getMake');
	    callNextFunction();

    	}
    	else if (currentField == 'make')
    	{
    		_nextFunctions = ['callPlayBall'];
		_nextFunctions.push('getRate');
		_nextFunctions.push('getModel');
		callNextFunction();
    	}
    	else if (currentField == 'model')
    	{
	       	    _nextFunctions = ['callPlayBall'];
	  	    _nextFunctions.push('getRate');
  		    callNextFunction();
    	}
    }
    
} // setFromFlash()


function findState(zip)
{
    var state = "";
    if (zip.length == 5 && all_states && all_zips)
    {
    	for (var i=0;i<all_zips.length-1;i++)
    	{
    	    var j = all_zips[i].indexOf(zip);
    	    if (j>=0)
    	      return all_states[i];
    	}
    }
    return state;
} // findState()


