var csel = {};

$(document).ready(function () {
    try {
        if ($("div#csBreadcrumb").length > 0) {
            $("div#breadcrumbs div")[0].innerHTML = $("div#csBreadcrumb")[0].innerHTML;
        }
    } catch (e) {
        // nothing
    }

    // scrollable tables
    $('table.csScrolltable thead tr').each(function () {
        var c = this.insertCell(this.cells.length);
        c.style.width = '26px';
    });
    $('table.csScrolltable').each(function () {
        var r = this.insertRow(this.rows.length);
        var c = r.insertCell(r.cells.length);
        c.style.height = '100%';
        c.innerHTML = '&nbsp;';
    });

    // Info bar menus
    $('.csInfoBarMenu').live('mouseover', function () {
        $(this).css('background-color', '#4D8B76');
        //$('#' + this.id + 'Popup').show();
        $('#' + this.id + 'Popup').css('left', $(this).offset().left + 'px').show();
    });
    $('.csInfoBarMenu').live('mouseout', function () {
        $(this).css('background-color', '');
        $('#' + this.id + 'Popup').hide();
    });
    $('.csInfoBarSubMenu').live('mouseover',
		function () {
		    $(this).css('background-color', '#f0f0f0');
		    $('#' + this.id + 'Popup').css({ left: $(this).offset().left + $(this).width() + 'px' }).show();
		});
    $('.csInfoBarSubMenu').live('mouseout', function () {
        $(this).css('background-color', '');
        $('#' + this.id + 'Popup').hide();
    }
	);
    // end info bar maenus

    // product page, images
    $('#csImageThumbs img').click(function () {
        $(this).ThumbClick();
    });
    $('.csDeleteProduct').click(function () {
        return confirm('Are you sure you want to delete this product?');
    });


    $('#csMainImagePane img').live('click', function () { $(this).ShowPic(); });

    // draw a fancy border around each of these
    $('div.csContainer').each(function () { $(this).ShadowBox(); });
    //    $('div.csContainer').each(function() { csel.ShadowBox(this); });
    csel.ShowRecentProducts();
    $('div#search input').val('Search our website...').addClass('watermark');
    $('div#search input').blur(function () { if ($(this).val() == '') { $(this).addClass('watermark'); $(this).val('Search our website...'); } });
    $('div#search input').focus(function () { if ($(this).val() == 'Search our website...') { $(this).val(''); } $(this).removeClass('watermark'); });
});

function cselAPI() {
};
cselAPI.prototype.ShowRecentProducts = function() {
	var sProds = csel.getCookie('RecentProducts');
	if(!sProds) return;
	var prods = sProds.split('^');
	if($('#csRecentProducts').length==0) {
		csel.AddInfoBarMenu('csRecentProducts', 'Recent Products');
	}
	for(var i=0; i<prods.length; i++) {
		var prod = prods[i].split('|');
		$('#csRecentProductsPopup>div')
			.append($('<a href="/viewproduct.aspx?prodid=' + prod[0] + '">' + prod[1] + '</a>'));
	}
};
cselAPI.prototype.AddInfoBarMenu = function(id, title) {
	$('#csInfoBarContainer')
		.append($('<div></div>')
					.attr({id: id})
					.hide()
					.addClass('csInfoBarMenu')
					.append('<span>' + title + '</span>')
					.append($('<div></div>')
						.attr({id: id + 'Popup'})
						.addClass('csInfoBarPopup')
						.append($('<h4>' + title + '</h4>'))
						.append($('<div></div>'))).fadeIn());
};
cselAPI.prototype.AddViewedProduct = function(ProdID, Description, Group) {
	var sProds = csel.getCookie('RecentProducts');
	var prods;
	if(sProds) {
		prods = sProds.split('^');
		// check if product already in list
		for(var i=0; i<prods.length; i++) {
			if(prods[i].split('|')[0]==ProdID) return;
		}
	} else {
		prods = [];
	};
	prods.push(ProdID + '|' + Description + '|' + Group);
	
	var recent = [];
	if(prods.length>0) {
		var start = prods.length-11;
		start = start<0?0:start;
		for(var i=prods.length-1; i>start; i--) {
			recent.push(prods[i]);
		}
	}
	csel.setCookie('RecentProducts', recent.join('^'), 31);
	csel.ShowRecentProducts();
};

cselAPI.prototype.setCookie = function(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
};

cselAPI.prototype.getCookie = function(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name)
	    {
	    return unescape(y);
	    }
  }
};


csel = new cselAPI();

// jquery plugin for showing an image
$.fn.ShowPic = function () {
    //	$(this).ShadowBox();
    var transDiv;
    transDiv = $('<div></div>')
				.addClass('transback').addClass('imagePopup')
				.css({ position: 'fixed',
				    zIndex: 9999,
				    left: '0px',
				    top: '0px',
				    width: '100%',
				    height: '100%'
				})
				.click(function () { $('.imagePopup').remove(); })
				.appendTo('body');

    var clone = $('<div></div>')
					.addClass('imagePopup')
					.css({ border: '10px solid black',
					    width: '50px',
					    height: '50px',
					    left: ($(window).width() / 2) - 25 + 'px',
					    top: ($(window).height() / 2) - 25 + 'px',
					    backgroundColor: 'white',
					    position: 'fixed',
					    zIndex: 10000
					})
					.attr('id', 'imageClone')
					.append($(this)
						.clone()
						.attr({ title: '' })
						.css({ width: 'auto',
						    display: 'none'
						})
						.load(function () {
						    var imH = $(this).height();
						    var imW = $(this).width();
						    var wH = $(window).height() - 50;
						    var wW = $(window).width() - 50;
						    var width, height;
						    if (wW < imW || wH < imH) {
						        if ((wW / wH) > (imW / imH)) {
						            height = wH;
						            width = height * (imW / imH);
						        } else {
						            width = wW;
						            height = width * (imH / imW);
						        }
						    } else {
						        width = imW;
						        height = imH;
						    }
						    $(this)
								.parent()
								.animate({ left: ($(window).width() / 2) - (width / 2) + 'px',
								    top: ($(window).height() / 2) - (height / 2) + 'px',
								    width: width + 'px',
								    height: height + 'px'
								}, 'fast', function () { $($(this).children()[0]).css({ maxWidth: width + 'px', maxHeight: height + 'px' }).fadeIn(); });
						})
					)
					.append($('<img></img>')
							.attr('src', '/portals/0/images/cancel_32.png')
							.css({ position: 'absolute',
							    right: '0px',
							    top: '0px',
							    marginRight: '-20px',
							    marginTop: '-20px',
							    cursor: 'pointer'
							})
							.click(function () { $('.imagePopup').remove(); })
							);
    $(clone).appendTo('body');
};
$.fn.ThumbClick = function() {
	$('#csMainImagePane')
		.empty()
		.append($('<img src="/images/loading.gif" alt="loading" />')
		.css({width: 'auto', height: 'auto', marginTop: '144px', marginLeft: '104px'}));
	$('<img></img>')
		.attr({src: $(this).attr('src').replace('Thumbnail.aspx?size=100&image=', '')})
		.load(function() { $('#csMainImagePane')
								.empty()
								.append($(this)); 
						});
//			$('#csMainImagePane img')
//			.attr({src: $(this).attr('src').replace('Thumbnail.aspx?image=', '')});

};
$.fn.ShadowBox = function () {
	 // test top margin of this.
    var fChild = $(this).children()[0];
    if (fChild) {
        if ($(fChild).css("margin-top") != '') {
            $(fChild).css("margin-top", "0px");
        }
    }
    var top = $('<div></div>').addClass('cs_top');
    var middle = $('<div></div>').addClass('cs_middle');
    var bottom = $('<div></div>').addClass('cs_bottom');
    top.append($('<div></div>').append($('<div></div>')));
    bottom.append($('<div></div>').append($('<div></div>')));
    var sib = $(this).prev();
    var parent = $(this).parent();
    var mid = $('<div></div>').append($(this));
    middle.append(mid);
    var cont = $('<div></div>').css("display", "inline-block");
    cont.append(top).append(middle).append(bottom);
    if (sib.length == 0) {
        $(parent).prepend(cont);
    } else {
        $(sib).after(cont);
    }
	return $(cont);
};

// Create a jquery plugin that prints the given element.
$.fn.print = function() {
    // NOTE: We are trimming the jQuery collection down to the
    // first element in the collection.
    if (this.size() > 1) {
        this.eq(0).print();
        return;
    } else if (!this.size()) {
        return;
    }

    // ASSERT: At this point, we know that the current jQuery
    // collection (as defined by THIS), contains only one
    // printable element.

    // Create a random name for the print frame.
    var strFrameName = ("printer-" + (new Date()).getTime());

    // Create an iFrame with the new name.
    var jFrame = $("<iframe name='" + strFrameName + "'>");

    // Hide the frame (sort of) and attach to the body.
    jFrame.css("width", "1px")
        .css("height", "1px")
        .css("position", "absolute")
        .css("left", "-9999px")
        .appendTo($("body:first"));

    // Get a FRAMES reference to the new frame.
    var objFrame = window.frames[strFrameName];

    // Get a reference to the DOM in the new frame.
    var objDoc = objFrame.document;

    // Grab all the style tags and copy to the new
    // document so that we capture look and feel of
    // the current document.

    // Create a temp document DIV to hold the style tags.
    // This is the only way I could find to get the style
    // tags into IE.
    var jStyleDiv = $("<div>").append(
        $("link").clone()
        ).append(
        $("style").clone()
        );
        
    var htm = this.html();

    // Write the HTML for the document. In this, we will
    // write out the HTML of the current element.
    objDoc.open();
    objDoc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    objDoc.write("<html>");
    objDoc.write("<body>");
    objDoc.write("<head>");
    objDoc.write("<title>");
    objDoc.write(document.title);
    objDoc.write("</title>");
    objDoc.write(jStyleDiv.html());
    objDoc.write("</head>");
    objDoc.write(this.html());
    objDoc.write("</body>");
    objDoc.write("</html>");
    objDoc.close();

    // Print the document.
    objFrame.focus();
    objFrame.print();

    // Have the frame remove itself in about a minute so that
    // we don't build up too many of these frames.
    setTimeout(
function() {
    jFrame.remove();
},
(60 * 1000)
);
}

// shopping cart script
var cartText;
$(document).ready(function () {
    // show add to order buttons
    $('a.csAddProd').show();
    $('a.csChooseProd').show();
    cartText = $('#csShoppingBar>span').text();
	
	$.get('/orders/get/', function(data) { $('#csShoppingBar').replaceWith($(data)) });

    // nice button images
    $('a.AddToCartLarge, a.CartDropDownLarge').hover(
        function () { $(this).css('background-position', '0px -25px') },
        function () { $(this).css('background-position', '0px 0px') }
    );
    $('a.AddToCartLarge, a.CartDropDownLarge').mousedown(
        function () { $(this).css('background-position', '0px -50px') }
    );
    $('a.AddToCartLarge, a.CartDropDownLarge').mouseup(
        function () { $(this).css('background-position', '0px -25px') }
    );
    $('a.csChooseProd').click(function (e) {
        $('div.csProdSelection').hide();
		$('div.csProdSelection2').hide();
        $('div#csPS' + this.id.replace('csChooseProd', '')).show();
    });
});

function SaveCookie(prods) {
    var s = [];
    for (var i = 0; i < prods.length; i++) {
        s.push(prods[i].StockProdID + '|' + prods[i].Description + '|' + prods[i].Quantity);
    }
    var cook = s.join('^');
    //alert(cook);
    csel.setCookie('ShoppingCart', cook, 31, '/');
};

function ProdClick() {
	$('div.csProdSelection').hide();
	$('div.csProdSelection2').hide();
};

function ConfirmClearList() {
	return confirm('Remove all products from your shopping cart - are you sure?');
};

