// attach event to load event
if ( document.addEventListener ) {
	document.addEventListener("DOMContentLoaded", cc_init, false);

} else if ( window.attachEvent ) {
	window.attachEvent("onload", cc_init);
}
var ps_showOnLoad = '';
var ps_style = '';
var ps_designid = '';
var ps_decorationType = 'E';
var po_httpRequest;
var ps_AJAXResponse;
var ps_sessionID;
var ps_skin = 'http://www.corporatecasuals.com/sell/basic.css';
var ps_buttonParams = new Array(100);
var pi_buttonIdx = 0;
var pb_isIE = navigator.userAgent.indexOf('MSIE') != -1;
var pb_testMode = false;

//config
var ps_btnDefWidth = '100';
var ps_btnDefShowLogo = 'Y';
var ps_btnDefShowProduct = 'Y';
var ps_btnDefCTA ='Buy Now&#187;';
var ps_btnDefMarkup = 2;

var ps_btnWidth = ps_btnDefWidth;
var ps_btnShowLogo = ps_btnDefShowLogo;
var ps_btnShowProduct = ps_btnDefShowProduct;
var ps_btnTitle = '';
var ps_btnCTA = ps_btnDefCTA;
var ps_btnAltLogo = '';
var ps_btnAltProduct = '';
var ps_btnSellReason = '';
var ps_lastButtonCache = '';
var ps_btnMarkup = ps_btnDefMarkup;

function cc_init(){	
	loadStyleSheet(ps_skin);
	ps_sessionID = makeGUID();
	
	// add windowshade
	var e = document.createElement("div");
	e.id = 'ccb_ws';						
	document.getElementsByTagName("body")[0].appendChild(e);
	
	if (ps_showOnLoad.length > 0){
		E('ccb_ws').style.display = 'block';
	}
	
	getButtons();	
	pi_buttonIdx = 0;
	processNextButton();				
}

function processNextButton(){
	
	// get params	
	try {
		var ls_temp = ps_buttonParams[pi_buttonIdx].split('|')
		var ls_designid = ls_temp[0];
		var ls_style = ls_temp[1];
		
		ps_btnWidth = ps_btnDefWidth;
		ps_btnShowLogo = ps_btnDefShowLogo;
		ps_btnShowProduct = ps_btnDefShowProduct;
		ps_btnTitle = '';
		ps_btnCTA = ps_btnDefCTA;
		ps_btnAltLogo = '';
		ps_btnAltProduct = '';
		ps_lastButtonCache = '';
		ps_btnMarkup = ps_btnDefMarkup;
		ps_btnSellReason = '';
			
		if (ls_temp.length > 2) ps_btnSellReason = ls_temp[2];			
		if (ls_temp.length > 3) ps_btnWidth = ls_temp[3];
		if (ls_temp.length > 4) ps_btnShowLogo = ls_temp[4];		
		if (ls_temp.length > 5) ps_btnShowProduct = ls_temp[5];
		if (ls_temp.length > 6) ps_btnTitle = ls_temp[6];
		if (ls_temp.length > 7) ps_btnCTA = ls_temp[7];
		if (ls_temp.length > 8) ps_btnAltLogo = ls_temp[8];
		if (ls_temp.length > 9) ps_btnAltProduct = ls_temp[9];	
		if (ls_temp.length > 10) ps_btnMarkup = ls_temp[10];								
	}
	catch(ex){
		ls_designid = null;
		ls_style = null;
	}
		
	// send request
	if ((ls_designid != null) && (ls_style != null)){			
		po_httpRequest = GETAJAXREQUEST();									   		
		var ls_request = 'http://www.corporatecasuals.com/sell/product.aspx?STYLE=' + ls_style + '&EID=' + ls_designid + '&IDX=' + pi_buttonIdx + '&RID=' + makeUniqueURLToken(ps_sessionID);
		sendRequest(ls_request);
		//po_httpRequest.open('get', ls_request);                
		//po_httpRequest.onreadystatechange = Product_Callback;
		//po_httpRequest.send(null);
		
	}
}

function getSetting(ai_buttonNumber, ai_settingIdx){
	var ls_temp = ps_buttonParams[ai_buttonNumber].split('|')
	return ls_temp[ai_settingIdx];
}

function getButtons(){
	pi_buttonIdx = 0;
	var ls_ctrl = 'ccb' + pi_buttonIdx;
	var lo_ctrl;
	var i;
	
	for(i=0; i<100; i++){
			
		try{
			lo_ctrl = E(ls_ctrl);
		}
		catch(ex){}
				
		if (lo_ctrl != null){			
			ps_buttonParams[pi_buttonIdx] = lo_ctrl.innerHTML;
			E('ccb' + pi_buttonIdx).style.display = 'none';
			pi_buttonIdx++;
			ls_ctrl = 'ccb' + pi_buttonIdx;							
		}
		else {
			lo_ctrl = null;	
			ls_ctrl = '';		
			return true;
		}
	}	
}

function processAJAXResponse() {
	Product_Callback(); 
}

function Product_Callback(){
	if(ps_AJAXResponse != ''){	
		//var ps_AJAXResponse = po_httpRequest.responseText;
		
    	var ls_Temp = ps_AJAXResponse.split('|');
		if (ls_Temp[1] == 'OK'){
		
			// button and panel id's
			var ls_buttonID = 'ccb' + pi_buttonIdx;
			var ls_panelID = 'ccp' + pi_buttonIdx;
			
			// add panel to the DOM
			var e = document.createElement("div");
			e.id = ls_panelID;						
			document.getElementsByTagName("body")[0].appendChild(e);
						
			// add click handler to button
			if (pb_isIE){
				E(ls_panelID).setAttribute('className','sellpanel');			
			}
			else {
				E(ls_panelID).setAttribute('class','sellpanel');			
			}				
			
			// process the button
			var ls_btn = ls_Temp[2];
			ps_lastButtonCache = ls_btn;
			ls_btn = ls_btn.replace(/%WIDTH%/gi, ps_btnWidth);
			E(ls_buttonID).style.width = ps_btnWidth;
			E(ls_buttonID).innerHTML = ls_btn;			
			var li_Price = Number(E('cc_lblBtnPrice' + pi_buttonIdx).getAttribute('value'));			
			
			if (ps_btnMarkup.length > 0){
				li_Price = li_Price + Number(ps_btnMarkup);
				E('cc_lblBtnPrice' + pi_buttonIdx).innerHTML = '$' + li_Price.toFixed(2);
			}
			else{
				li_Price = li_Price + ps_btnDefMarkup;				
				E('cc_lblBtnPrice' + pi_buttonIdx).innerHTML = '$' + li_Price.toFixed(2);			
			}								
			
			// process the panel
			E(ls_panelID).innerHTML = ls_Temp[3];			
			
			// post processing
			if (ps_btnSellReason.length > 0) E('cc_lbltitle' + pi_buttonIdx).innerHTML = ps_btnSellReason;
			if (ps_btnShowLogo == 'Y'){
				E('cc_imgBtnLogo' + pi_buttonIdx).style.display = 'block';
			}
			else {
				E('cc_imgBtnLogo' + pi_buttonIdx).style.display = 'none';
			}
			
			if (ps_btnShowProduct == 'Y') {
				E('cc_imgBtnProduct' + pi_buttonIdx).style.display = 'block';
			}
			else {
				E('cc_imgBtnProduct' + pi_buttonIdx).style.display = 'none';
			}
			if (ps_btnTitle.length > 0) E('cc_lblBtnTitle' + pi_buttonIdx).innerHTML = ps_btnTitle;		
			if (ps_btnCTA.length > 0) E('cc_lblBtnCTA' + pi_buttonIdx).innerHTML = ps_btnCTA;
			if (ps_btnAltLogo.length > 0) E('cc_imgBtnLogo' + pi_buttonIdx).src = ps_btnAltLogo;
			if (ps_btnAltProduct.length > 0) E('cc_imgBtnProduct' + pi_buttonIdx).src = ps_btnAltProduct;	
			if (ps_btnMarkup.length > 0) E('cc_txtMarkup' + pi_buttonIdx).value = ps_btnMarkup;	
			
			// show on load
			if (parseInt(ps_showOnLoad) == pi_buttonIdx){				
				burp('SOD');
				E(ls_buttonID).style.display = 'none';
				showPanel(ps_showOnLoad);
			}
			E('ccb' + pi_buttonIdx).style.display = 'block';			
			
			pi_buttonIdx++;
			processNextButton();		
	    }
	    else {
			E('ccb' + pi_buttonIdx).innerHTML = 'ERROR: Invalid design or style';			
	    }	    
	}
}

function rebuildButton(as_idx, as_buttonId, as_width, as_showProduct, as_showLogo, as_title, as_cta, as_altLogoImg, as_altProductImg, as_markup, as_reason){
	var ls_btn = ps_lastButtonCache;
	ls_btn = ls_btn.replace(/%WIDTH%/gi, as_width);
	E(as_buttonId).style.width = as_width;
	E(as_buttonId).innerHTML = ls_btn;
	if (as_showLogo == 'Y'){
		E('cc_imgBtnLogo'+ as_idx).style.display = 'block';
	}
	else {
		E('cc_imgBtnLogo'+ as_idx).style.display = 'none';
	}
	
	if (as_showProduct == 'Y'){
		E('cc_imgBtnProduct'+ as_idx).style.display = 'block';
	}
	else {
		E('cc_imgBtnProduct'+ as_idx).style.display = 'none';
	}
	if (as_title.length > 0) E('cc_lblBtnTitle'+ as_idx).innerHTML = as_title;
	if (as_cta.length > 0) E('cc_lblBtnCTA'+ as_idx).innerHTML = as_cta;
	if (as_altLogoImg.length > 0) E('cc_imgBtnLogo'+ as_idx).src = as_altLogoImg;
	if (as_altProductImg.length > 0) E('cc_imgBtnProduct'+ as_idx).src = as_altProductImg;	
	
	var li_Price = Number(E('cc_lblBtnPrice' + as_idx).getAttribute('value'));		
	
	if (as_markup.length > 0){	
		li_Price = li_Price + Number(as_markup);
		E('cc_lblBtnPrice' + as_idx).innerHTML = '$' + li_Price.toFixed(2);
		E('ccp_price' + as_idx).innerHTML = '$' + li_Price.toFixed(2);
	}
	else {
		li_Price = li_Price + ps_btnDefMarkup;				
		E('cc_lblBtnPrice' + as_idx).innerHTML = '$' + li_Price.toFixed(2);
		E('ccp_price' + as_idx).innerHTML = '$' + li_Price.toFixed(2);
	}					
}

function showPanel(as_idx){
	var li_panelId = 'ccp' + as_idx;
	var li_markup = Number(getSetting(parseInt(as_idx), 10))
	var li_price = Number(E('ccp_price' + as_idx).getAttribute('value'));

	if (isNaN(li_markup)){		
		li_price += 2;  // default commission	
	}
	else{
		li_price += li_markup;
	}
	if (String(document.location).indexOf('sellstudio.aspx',0) < 0){
	burp('here');	
		E('ccp_price' + as_idx).innerHTML = '$' + li_price.toFixed(2);
	}
	
	E(li_panelId).style.display = 'block';	
	E('ccb_ws').style.display = 'block';
	CENTERTHIS('ccp0');					
}

function CENTERTHIS(as_id){
	var li_winW;
	var li_winH;
	var li_elemW;
	var li_elemH;

	if(pb_isIE){
		li_winW = document.body.clientWidth;
		li_winH = document.body.clientHeight;
	}
	else{
		li_winW = window.innerWidth;
		li_winH = window.innerHeight;
    }

	li_elemW = 500;
	li_elemH = 300;
	
	E(as_id).style.top = (li_winH/2) - (li_elemH/2);
	E(as_id).style.left = (li_winW/2) - (li_elemW/2);

}

function hidePanel(ai_idx){
	E('ccp' + ai_idx).style.display = 'none';
	E('ccb_ws').style.display = 'none';
	
	
	if (String(document.location).indexOf('corporatecasuals.com/sell.aspx',0) > 0){		
		document.location = '/';
	}
}

function swapImg(ai_idx){
	var ls_mainURL = E('cc_imgMain' + ai_idx).src;
	E('cc_imgMain' + ai_idx).src = E('cc_imgThumb' + ai_idx).src;
	E('cc_imgThumb' + ai_idx).src = ls_mainURL;
}

function buyNow(ai_idx){
	var ls_size = E('cc_txtSize' + ai_idx).value;
	var ls_color = escape(E('cc_txtColor' + ai_idx).value);
	var li_qty = E('cc_txtQuantity' + ai_idx).value;
	var ls_style = E('cc_txtStyle' + ai_idx).value;
	var ls_design = E('cc_txtDesign' + ai_idx).value;
	var ls_homePage = escape(document.location);
	
	if (pb_testMode){
		alert('*** Buy Item Click Results ***\nStyle: ' + ls_style + '\nColor: ' + E('cc_txtColor' + ai_idx).value + '\nSize: ' + ls_size + '\nQuantity: ' + li_qty + '\n\n');
	}
	else {

		
		var ls_url = 'http://www.corporatecasuals.com/sell/buy.aspx';
		ls_url += '?Style=' + ls_style;
		ls_url += '&Color=' + ls_color;
		ls_url += '&Size=' + ls_size;
		ls_url += '&Qty=' + li_qty;
		ls_url += '&D1=' + ls_design;
		ls_url += '&URL=' + ls_homePage;
		ls_url += '&Markup=' + getSetting(parseInt(ai_idx), 10);
		//alert(ls_url);
		document.location = ls_url;	
	}
}

//------------------- utility functions
function E(as_name){
	return document.getElementById(as_name);
}

function GETAJAXREQUEST(){
	var ps_browser = navigator.appName;
    if(ps_browser == "Microsoft Internet Explorer"){
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        return new XMLHttpRequest();
    }
}

function FINDPOS(obj) {	
	var curleft = curtop = 0;
	if (obj.offsetParent){
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;

		} while (obj = obj.offsetParent);

		return {x:curleft,y:curtop};		
	}
}

// creates a unique request token by parsing the users guid and a random number
function makeUniqueURLToken(as_GUID){
	return '&REQUESTID=' + as_GUID + '_' + String(Math.floor(Math.random() * 0xFFFFFF))
}

// well not a GUID, but pretty darn unique anyway
function makeGUID(){
	var g ='';
	for(var i = 0; i < 32; i++){
		g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "" : "");
	}	
	
	return g;
}

function loadStyleSheet(as_Style){	
	var e = document.createElement('link');
	e.href = as_Style;
	e.type = 'text/css';
	e.rel = 'stylesheet';
	document.getElementsByTagName("head")[0].appendChild(e);	
}

var ps_ajaxProxy = ''
var ps_AJAXResponse = '';		//stores the js ajax response
var ps_JSAJAXResponse = ''

function sendRequest(url) {

	var ls_RequestToken = makeUniqueURLToken(ps_sessionID);	
    burp('REQUEST: ' + ps_ajaxProxy + '?Request=' + url);
	
	// use the JS based ajax call if ajaxproxy is left blank
	if ((ps_ajaxProxy == 'JS') || (ps_ajaxProxy == '')){
	
		// add a script tag to the document
		ps_JSAJAXResponse = '';
		po_AJAXScriptTag = document.createElement('SCRIPT');
		po_AJAXScriptTag.type = 'text/javascript';			
		po_AJAXScriptTag.src = url + ls_RequestToken + '&ResponseMethod=JS';
		po_AJAXScriptTag.id = 'AJAXRESPONSE';
		document.getElementsByTagName("head")[0].appendChild(po_AJAXScriptTag)
		
		// configure the callback routine
		var lo_testFunction = JSAJAXCheckComplete;
		var lo_timeoutFunction = JSAJAXTimeout;
		var lo_finalizeFunction = handleResponse;    	
		callback(lo_testFunction, lo_timeoutFunction, lo_finalizeFunction);	
	}
	else if (ps_ajaxProxy != '') {
		httpRequest.open('get', ps_ajaxProxy + '?Request=' + escape(url + ls_RequestToken));
		httpRequest.onreadystatechange = handleResponse;
		httpRequest.send(null);		
	}
	else {
		alert('Error.  Your ajaxproxy setting is incorrect.');
	}
}


function JSAJAXCheckComplete(){	
	if (ps_JSAJAXResponse != '') {			
		return true;
	}
	else {
		return false;
	}
}

function JSAJAXTimeout(){
	alert('JS AJAX Timeout');
}

function handleResponse(){
	burp('finalize');
	if ((ps_ajaxProxy == 'JS') || (ps_ajaxProxy == '')){
		ps_AJAXResponse = ps_JSAJAXResponse;		
		document.getElementsByTagName("head")[0].removeChild(document.getElementById('AJAXRESPONSE'));			
		ps_JSAJAXResponse = '';
		burp(ps_AJAXResponse);
	}	
	else if (ps_ajaxProxy != '') {
		if(httpRequest.readyState == 4){		
			ps_AJAXResponse = httpRequest.responseText;			
		}
	}
	
	processAJAXResponse();
}

var mi_callbackTimeout = 60;
var mi_callbackTimeoutCount = 0;
var mi_callbackTickInterval = 100;
var mo_callbackCheckFunction;
var mo_callbackTimeoutFunction;
var mo_callbackCompleteFunction;
var mo_callbackTimer; 

function callback(ao_checkFunction, ao_TimeoutFunction, ao_CompletedFunction){
    mi_callbackTimeoutCount = 0;
    mo_callbackCheckFunction = ao_checkFunction;
    mo_callbackTimeoutFunction = ao_TimeoutFunction;
    mo_callbackCompleteFunction = ao_CompletedFunction;       
    renderTimer = self.setInterval('callbackCheck()', mi_callbackTickInterval);    
}

function callbackCheck(){
    mi_callbackTimeoutCount++;
    //burp(mi_callbackTimeoutCount);
        
    if (mi_callbackTimeoutCount <= mi_callbackTimeout){
        if (mo_callbackCheckFunction()){
            window.clearInterval(renderTimer);
            return mo_callbackCompleteFunction();
        }        
    }
    else if (mi_callbackTimeoutCount > mi_callbackTimeout) {
        window.clearInterval(renderTimer);
        return mo_callbackTimeoutFunction();
    }  
}

// function creates and initializes the standard AJAX object
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

function burp(as_message){
	try{
		console.log(as_message);
	}
	catch(ex){}
}