var lastPLSWhich = '*';
var lastPLSPage = 0;
var lastPLSLink = null;
var plsPerPage = { rows : 10, matrix : 30 };
var ffURL = 'http://www.furniturefinders.com/dboffice/';
//var ffURL = 'http://localhost/dboffice/';
var ffReceiveCB = '';

var catMap = { 
    chairs : 'Chairs',
    cubicles : 'Cubicles',
    desks : 'Desks',
    tables : 'Conference Tables',
    filing : 'File Cabinets',
    reception : 'Reception Area',
    parts : 'Parts and Accessories',
    all : '*' 
};

var catMapReverse = {};
for (var k in catMap) {
	catMapReverse[catMap[k]] = k;
}

function plsRemoveClass(elt, name)
{
    var re = new RegExp('\\b' + name + '\\b')
    if (elt.className)
        elt.className = elt.className.replace(re, '')
}

function plsSeparator()
{
    return '?';
}

function plsResolveWhich() {
    var result = '';
    if (window.plsCategory) {
        var s = window.plsCategory;
        if (catMap[s]) {
            result = s;
        }
    }
    if (! result) {
        result = plsWhichFromURL();
    }
    return result;
}

function plsPageFromURL()
{
	var m = /\bpage:(\d+)/.exec(location.href);
    return m ? m[1] : 0;
}

function plsWhichFromURL()
{
    var which = '*';
    var l = location.href;
    var sep = plsSeparator();
    var idx = l.indexOf(sep);
    if (idx > 0) {
        var s = l.substr(idx+1)
        if (s) {
        	var idx2 = s.indexOf('&');
        	if (idx2 > 0) {
        		s = s.substr(0, idx2);
        	}
        }
        if (catMap[s])
            which = s;
    }
    return which;
}

function plsAddClass(elt, name)
{
    elt.className += ' ' + name;
}

function plsSwitch(no, which)
{
    var header = $('pls-header');
    if (header) {
        if (window.lastPLSLink)
            plsRemoveClass(window.lastPLSLink, 'current');
        var tagElements = header.getElementsByTagName('a');
        var elt = tagElements[no];
        plsAddClass(elt, 'current');
        window.lastPLSLink = elt;
    }
    if ((arguments.length == 1) || (which == ''))
        which = '*';

    if (catMapReverse[which]) {
    	which = catMapReverse[which];
    }
    
    if (catMap[which]) {
        var l = location.href;
        var sep = plsSeparator();
        var idx = l.indexOf(sep);
        if (idx > 0) 
            l = l.substr(0, idx);
        if (which != 'all')
            l = l + sep + which;
        if (l != location.href)
            location.href = l;
    } else {
        plsRefresh(which);
    }
}

function plsSetCookie(cookieName, cookieValue, nDays)
{
    var s = cookieName + "=" + escape(cookieValue);
    if (nDays) {
        var today = new Date();
        var expire = new Date();
        expire.setTime(today.getTime() + 3600000*24*nDays);
        s += ";expires="+expire.toGMTString();
    }
    document.cookie = s;   
}

function plsDeleteCookie(cookieName)
{
    plsSetCookie(cookieName, '', -10);
}

function plsCookieExists(cookieName)
{
    var c = "" + document.cookie;
    var i1 = c.indexOf(cookieName + '=');
    return (i1 >= 0);
}

function plsReadCookie(cookieName) 
{
     var result = '';
     if (cookieName != '') {
        var c = "" + document.cookie;
        var i1 = c.indexOf(cookieName + '=');
        if (i1 >= 0) {
            result = c.substr(i1 + cookieName.length + 1);
            var i2 = result.indexOf(';');
            if (i2 > 0) 
                result = result.substr(0, i2);
            result = unescape(result);
        }
     } 
     return result;
}

function plsSetCB(code)
{
    window.ffReceiveCB = code;
}

function plsLoaded(data)
{
    if (data.indexOf('dealer-listings') == -1)
        data = '<br><br><b>No inventory available.</b>';
    else {
        // rewrite the navigation-bar links (if any):
        data = data.replace(/href="[^"]+index.php.off=(\d+)[^"]+"/g, 
                           'href="javascript:plsGotoPage($1)"');
    }
    var elt = $('pls-inventory');
    if (elt) {
        elt.innerHTML = data;
        window.scrollTo(0, 0);
        if (window.plsMoreInfoURL || window.plsProductURL) {
            setTimeout(fixupMoreInfoLinks, 500);
        }
        if (window.plsPostProcess) {
            setTimeout(plsPostProcess, 500);
        }
    }
}

function each(f, arr) {
    var l = arr.length;
    for (var i = 0; i < l; i++) { f(arr[i]) }
}

function fixupMoreInfoLinks() {
    var elt = $('pls-inventory');
    var isRowTitle = /\brow-title\b/;
    var isMoreLink = /\brow-link\b/;
    var adId       = /[&?]id=(\d+)/;
    
    var productURL = window.plsMoreInfoURL || window.plsProductURL;
    each(function(rowTitle) {
        var cl = rowTitle.className;
        if (cl && cl.match(isRowTitle)) {
            each(function(a) {
                //var cl = a.className;
                //if (cl && cl.match(isMoreLink)) {
                    var m = adId.exec(a.href);
                    if (m) {
                        a.href = productURL + m[1];
                    }
                //}
            }, rowTitle.getElementsByTagName('A'));
        }
    }, elt.getElementsByTagName('DIV'));
}

function plsGotoPage(off)
{
	if (1) {
		var url = location.href;
		var m = /\bpage:(\d+)/.exec(url);
		if (m) {
			var rep = (off > 0) ? ("page:" + (off+1)) : '';
			url = url.replace(/\bpage:\d+/, rep)
		} else {
			var sep = (url.indexOf('?') > 0) ? '&' : '?';
			url += sep + 'page:' + (off+1);
		}
		url = url.replace(/\?&/, '?');
		url = url.replace(/[?&]$/, '');
		location.href = url;
	} else {
		window.scrollTo(0, 0);
		plsRefresh(window.lastPLSWhich, off);
	}
}

function plsGetProductURL(url) 
{
    // relative product URL - 'absolutize' it
    if (url.substr(0, 4) != 'http') {
        var currentURL = window.location.href;
        var idx = currentURL.lastIndexOf('/');
        url = currentURL.substr(0, idx+1) + url;
    }
    if (!url.match(/\?$/)) {
        url = url + '?';
    }
    return escape(url);
}

function plsRefresh(which, off)
{
    var FFDealerID      = window.plsDealerID;
    if (!FFDealerID) {
        alert('Missing Dealer ID');
        return;
    }

    var plsWebsite      = window.ffURL;
    var plsSearchURL    = "index.php?page=dlr_search_css&s_res=AND";
    var plsSearchParams = "&cid=1&f_mysite=1&s_by=f_feat&uid=" + FFDealerID;

    if ((arguments.length == 0) || (which == ''))
        which = '*';

    var url = plsWebsite + plsSearchURL + plsSearchParams + "&js=1";
    if (which != '*') {
        var urlWhich = escape(which);
        if (catMap[which])
            urlWhich = encodeURIComponent(catMap[which]);
        url += "&f_prod_cat_ex=" + urlWhich;
    }

    var offArg = 0;
    if (arguments.length > 1)
        offArg = off;

    if (offArg)
        url += '&off=' + offArg;
    window.lastPLSPage = offArg;

    if (!window.plsLayout) {
        window.plsLayout = 'rows';
    }
    if (window.plsLayout == 'matrix') {
        url += '&hw_layout=matrix';
        if (window.plsMatrixPerRow)
            url += '&matrix_ads_per_row=' + window.plsMatrixPerRow;
        if (window.plsMatrixPerPage)
            url += '&matrix_ads_per_page=' + window.plsMatrixPerPage;
    }
    if (window.plsExtra)
        url += '&' + window.plsExtra;
    if (window.plsProductURL)
        url += '&product_url=' + plsGetProductURL(window.plsProductURL);

    var elt = $('pls-inventory');
    elt.innerHTML = '<div style="position:absolute;"' +
                    ' class="pls-loading-label">' +
                    'Loading Inventory' +
                    '</div>' + elt.innerHTML;

    //document.body.innerHTML = '<div>' + url + '</div>' + document.body.innerHTML;
    //alert(url);

    window.lastPLSWhich = which;
    plsSetCB(plsLoaded);
    plsCallJS(url);
}

function plsCallJS(url, id)
{
    var head = document.getElementsByTagName('head').item(0);
    if (!id) {
    	id = 'lastLoadedCmds';
    }
	var old  = $(id);
	if (old) {
        head.removeChild(old);
	}
	script = document.createElement('script');
	script.src   = url;
	script.type  = 'text/javascript';
	//script.defer = true;
	script.id = id;
	void(head.appendChild(script));
}

function plsDisplayPrintIcon()
{
	var elt = $('pls-ad-info');
	var d = document.createElement('A');
	//d.id = 'pls-ad-print-icon';
	d.className = 'pls-ad-print-icon';
	/*
	d.style.border = 'none';
	d.style.display = 'block';
	//d.style.paddingLeft = '35px';
	d.style.position = 'absolute';
	d.style.height = '30px';
	d.style.left = '10px;';
	d.style.top = '10px;';
	d.style.lineHeight = '30px';
	d.style.paddingLeft = '40px';
	var i = new Image();
	var bgURL = window.ffURL  + 'img/print1.png';
	i.src = bgURL;
	d.style.background = 'url(' + bgURL + ') no-repeat';
	*/
	d.href = location.href + '&print=1';
	d.target = '_blank';
	d.innerHTML = 'Click to print';
	elt.insertBefore(d, elt.firstChild);
}

function plsHide(id)
{
	var elt = $(id);
	if (elt) {
		elt.style.display = 'none';
	}
	
}

function plsAdLoaded(data)
{
	var elt = $('pls-ad-info');
    if (elt) {
    	if (plsIsPrint()) {
    		
    		var removed = elt.parentNode.removeChild(elt);
    		var body = document.getElementsByTagName("BODY")[0];
    		body.insertBefore(removed, body.firstChild);
    		
    		//body.style.fontFamily = 'Verdana,Arial,Helvetica,sans-serif';
    		//body.style.fontSize = '11px';
    		
    		body.style.padding = '0px';
    		body.style.margin = '0px';
    		
    		body.style.backgroundColor = '#fff';
    		body.style.backgroundImage = 'none';
    		
    		elt = removed;
    		elt.style.border = 'none';
    		elt.style.margin = '0px';
    		//elt.style.border = '1px solid black';
        }
    	if (window.plsPageAfterProductLoaded) {
            data = window.plsPageAfterProductLoaded(data);
        }
        elt.innerHTML = data;
        if (elt.isPrint) {
        	var tbl = $('pls-ad-info-tbl-main');
    		if (tbl) {
    			tbl.style.margin = '0px';
    			tbl.style.width = 'auto';
    		}
    		
    		plsHide('arrow-left');
    		plsHide('arrow-right');
    		plsHide('img-see-larger');
    		
    		var left = $('pls-ad-info-main');
    		var right = $('pls-ad-info-additional');
    		if (left && right) {
    			left.style.styleFloat = 'left';
    			left.style.cssFloat = 'left';
    			left.style.width = '48%';
    			right.style.styleFloat = 'left';
    			right.style.cssFloat = 'left';
    			right.style.width = '48%';
    		}
    		window.print();
        } else {
        	plsDisplayPrintIcon();
        }
    }
}

function plsIsPrint()
{
	return (location.href.indexOf('&print=1') > 0);
}

function plsShowProduct()
{
    var adId = 0;
    var l = location.href;
    l = l.replace(/\/+$/, '');
    var url = '';
    var sep = '?';
    if (window.plsProductIdSeparator) {
        sep = window.plsProductIdSeparator;
    }

    var idx      = l.lastIndexOf(sep);
    if (idx != -1) {
        adId = l.substr(idx+sep.length);
    }
    if (!adId.match(/^\d+/)) {
        adId = 0;
    } else {
        adId = parseInt(adId);
    }
    if (adId) {
        var dlrInfoURL  = "index.php?page=dlr_out&lookid=1&id=" + adId;
        url = window.ffURL + dlrInfoURL + "&js=1";
    }
    if (url) {
        
    	var isPrint = plsIsPrint();
    	var elt = $('pls-ad-info');
    	if (isPrint) {
    		var body = document.getElementsByTagName("BODY")[0];
    		var l = body.childNodes;
    		for (var i = 0; i < l.length; i++) {
    			if (l[i].style) {
    				l[i].style.display = 'none';
    			}
    		}
    		/*
    		while (body.firstChild) {
    			body.removeChild(body.firstChild);
    		}
    		*/
    		
    		elt.isPrint = true;
    		
    		// include print.css
    		var headID = document.getElementsByTagName("head")[0];         
            var cssNode = document.createElement('link');
            cssNode.type = 'text/css';
            cssNode.rel = 'stylesheet';
            cssNode.href = window.ffURL + 'img/print.css';
            cssNode.media = 'screen';
            headID.appendChild(cssNode);
            
            url += '&print=1';
            
            
    	} else {
    		elt.innerHTML = '<div>Loading Product...</div>';
    	}
//        document.body.innerHTML = '<div>' + url + '</div>' + document.body.innerHTML;
        plsSetCB(plsAdLoaded);
        plsCallJS(url);
    }
}

function plsSwitchLayout()
{
    if (!window.plsLayout) {
        window.plsLayout = 'rows';
    }
    if (window.plsLayout == 'matrix') {
        window.plsLayout = 'rows';
    } else {
        window.plsLayout = 'matrix';
    }
    plsSetCookie('layout', window.plsLayout, 0);
    // convert the page number:
    if (window.lastPLSPage > 0) {
    	// from matrix to rows:
    	var page = window.lastPLSPage;
    	if (window.plsLayout == 'rows') {
    		var r = plsPerPage.matrix / plsPerPage.rows;
    		page = window.lastPLSPage * r; 
    	} else {
    		var first = 1 + plsPerPage.rows * window.lastPLSPage;
    		page = Math.floor(first / plsPerPage.matrix);
    	}
    	if (page != window.lastPLSPage) {
    		window.lastPLSPage = page;
    		plsGotoPage(page);
    	}
    }
    plsRefresh(window.lastPLSWhich, window.lastPLSPage);
}

function OpenPreview(s_url) 
{
    var w_s = 50;
    var h_s = 50;
    var w = window.screen.width;
    var h = window.screen.height;
    return popUp(s_url,'PreviewWin', w_s, h_s, w-2*w_s, h-2*h_s-50);
}

function OpenImages(id,f)
{
  var url = window.ffURL + 'index.php?page=images&id='+id+'&f='+f;
  var w = OpenPreview('');
  var d = w.document;
  var s = '<html>' +
            '<body style="overflow:auto;margin:0;padding:0;">' +
            '<ifr' + 'ame' +
            ' name="images_frame"' +
            ' width="100%"' +
            ' height="100%"' +
            ' frameborder=0' +
            ' src="' + url + '" ' +
            ' marginwidth="0"' +
            ' marginheight="0"' +
            ' vspace="0"' +
            ' hspace="0"' +
            ' allowtransparency="true"' +
            ' scrolling="yes">' +
            '</ifr' + 'ame>' +
            '</body>' +
            '</html>';
   d.write(s);
   d.close();
}

window.popupWins = new Array();

function popUp (sURL, sName, x, y, dx, dy) {

    if ( typeof( window.popupWins[name] ) != "object" ){
        window.popupWins[name] = 
            window.open(sURL, sName, 'left='+x+',top='+y+',width='+dx+',height='+dy+',scrollbars=1,resizable=1');
    } else {
        if (!window.popupWins[name].closed) {
            if (sURL != '')
                window.popupWins[name].location.href = sURL;
        } else {
            window.popupWins[name] = 
                window.open(sURL, sName, 'left='+x+',top='+y+',width='+dx+',height='+dy+',scrollbars=1,resizable=1');
        }
    }

    window.popupWins[name].focus();
    return window.popupWins[name];

}

function $(id) { return document.getElementById(id); }

function plsImportDefaultStylesheet()
{
    var elts = document.getElementsByTagName("link");
    var found = 0;
    var firstStylesheet = 0;
    for (var i = 0; i < elts.length; i++) {
        var elt = elts[i];
        if (elt.type.toLowerCase() == 'text/css') {
            if (! firstStylesheet) {
                firstStylesheet = elt;
            }
            var h = elts[i].href;
            if (h.match(/dealers.css$/)) {
                found = 1;
                break;
            }
        }
    }
    if (! found) {

        var headID = document.getElementsByTagName("head")[0];         
        var cssNode = document.createElement('link');
        cssNode.type = 'text/css';
        cssNode.rel = 'stylesheet';
        cssNode.href = window.ffURL + 'img/dealers.css';
        cssNode.media = 'screen';
        // insertBefore the 1st CSS link - this works in all browsers,
        // but has no effect in IE, thus the next IE-specific step:
        headID.insertBefore(cssNode, firstStylesheet);

        // for IE - shift the stylesheet hrefs so that dealers.css
        // becomes the 1st on the list:
        if (document.all) {
            var ss = document.styleSheets;
            if (ss.length > 1) {
                var dealersHref = ss[ss.length-1].href;
                var dealersRules = ss[ss.length-1].rules;
                for (var j = ss.length-1; j > 0; j--) {
                    //ss[j].href = ss[j-1].href;
                    ss[j].rules = ss[j-1].rules;
                }
                //ss[0].href = dealersHref;
                ss[0].rules = dealersRules;
            }
        }
    }
}

if ($('pls-inventory')) {
    if (plsCookieExists('layout')) { 
        window.plsLayout = plsReadCookie('layout');
    }
    var page = plsPageFromURL();
    if (page) {
    	page--;
    }
    plsRefresh(plsResolveWhich(), page);
}
if ($('pls-ad-info'))
    plsShowProduct();

plsCallJS(window.ffURL + '/img/prevNext.js', 'prevNext');

//plsImportDefaultStylesheet();
