var ap = "";

var br;
var rt;
var mc;
var cz;
var ci;
var czw;
var mm;

//Home Backgrounds
var bgs = new Array('photos/backgrounds/new/bg-model-glass.jpg','photos/backgrounds/new/bg-detail-distinction.jpg','photos/backgrounds/new/bg-blue-gf.jpg','photos/backgrounds/new/bg-black-check.jpg','photos/backgrounds/new/bg-model-abacab.jpg','photos/backgrounds/new/bg-cherry-stripe-collar.jpg', 'photos/backgrounds/new/bg-4square-bold.jpg','photos/backgrounds/new/bg-model-navy-check.jpg','photos/backgrounds/new/bg-blue-pattern-fabric.jpg','photos/backgrounds/new/bg-pure-pink.jpg','photos/backgrounds/new/bg-turnback-cuff.jpg','photos/backgrounds/new/bg-navy-check.jpg','photos/backgrounds/new/bg-trevi-white.jpg');
var bgc,next,prev,timer,loaded_images=new Array(),num_loaded=0,first=true,clicked=false;
var fadeDuration=1500;
var slideDuration=5000;
var currentIndex=0;
var nextIndex=1;
var this_canvas;


//Debug
var db;

//Collections
var win,pp,stops,stop=1,products,active,active_index,active_wrap,clone,sib,collision_timer,lt,li=0,ns;


$(document).ready(function(){
	db = $('#debug');
	
	/*var html5canvas = typeof HTMLCanvasElement != undefined ? 1:0;
	
	alert(html5canvas);*/
	
	$('a.lb').prettyPhoto({ theme:'dark_rounded' });
	
	if( $('#burns-home').length ){
		mc = "home";
		setupHome();
		this_canvas = prev = $('#bh-canvas-current');
		next = $('#bh-canvas-next');
	}else if( $('#collections-browser').length ){
		mc = "collections";
		cz = '.product-preview';
		ci = '.zoomer';
		czw = '.zoom-window';
		resizeCollections();
		setupCollections();
		setupBrowser('c');
	}else if( $('#cart-view').length ){
		mc = "cart";
		resizeCart();
		var no_items = $('.itemContainer','.simpleCart_items').length;
		if( no_items <= 0 ){
			$('.simpleCart_checkout').hide();
		}	
	}else if( $('#checkout-view').length ){
		mc = "checkout";
		resizeCheckout();
		$("a[rel='hint']").colorbox();
	}else if( $('#shirt-view').length ){
		mc = "shirt";
		cz = ".component-view";
		ci = ".component";
		czw = ".zoom-window-shirt";
		
		var repo = (480-$('.shirt-info').height())/2;
		
		$('.shirt-info').css({ 'margin-top':repo+'px' });
		
		resizeShirt();
		
		var ss = $(ci).attr('alt');
		
		if( ss == "The Cloth" ){
			setupZoom('photos/the-shirt/the-cloth.jpg');
		}else if( ss == "The Cut" ){
			setupZoom('photos/the-shirt/the-cut.jpg');
		}else if( ss == "The Collar - Milanese" ){
			setupZoom('photos/the-shirt/the-collar-milanese.jpg');
		}else if( ss == "The Collar - Super Spread" ){
			setupZoom('photos/the-shirt/the-collar-superspread.jpg');
		}else if( ss == "The Cuff - Skinny Barrel" ){
			setupZoom('photos/the-shirt/the-cuff-skinny.jpg');
		}else if( ss == "The Cuff - Two-Button Barrel" ){
			setupZoom('photos/the-shirt/the-cuff-two-button.jpg');
		}else if( ss == "The Cuff - Turnback" ){
			setupZoom('photos/the-shirt/the-cuff-turnback.jpg');
		}else if( ss == "The Cuff - Oversized Cutaway French" ){
			setupZoom('photos/the-shirt/the-cuff-french-cutaway.jpg');
		}else{
			setupZoom('photos/the-shirt/the-cloth.jpg');
		}
	}else if( $('#press-view').length ){
		mc = "press";
		pp = $('.press-view');
		resizePress();
		setupBrowser('p');
		setupPress();
	}else if( $('.contact-view').length ){
		mc = "contact";
		resizeContact();
	}
	
	$(window).resize(function(){
		resizeTimer();	
	});	
});

function setupHome()
{
	$(window).resize(function(){
		resizeTimer();
	});
	
	/*if (window.G_vmlCanvasManager)
	{
	    var canvas1 = window.G_vmlCanvasManager.initElement('#bh-canvas-next');
	    //var canvas2 = window.G_vmlCanvasManager.initElement(canvas);
	}*/
	
	
	$('#bh-canvas-current').css({ 'opacity':0 });
	$('#bh-canvas-next').css({ 'opacity':0 });
	
	loadBackgrounds();
	
	$('#bg-thumbs img').click(function(){
		clicked = true;
		bgThumbClick(parseInt($(this).attr('in')));
	})
	
	burnsWindow();	
}

function loadBackgrounds()
{
	for(var bgl=0;bgl<bgs.length;bgl++)
	{
		 loaded_images[bgl] = new Image();
		 loaded_images[bgl].src = bgs[bgl];
		 loaded_images[bgl].onload = function(){ countBackgrounds() };
	 }	 
}

function countBackgrounds()
{
	num_loaded++;
	
	if( num_loaded == 3 )
	{
		drawToCanvas(this_canvas,currentIndex);
		$('.loader-box').remove();	
	}
}


function drawToCanvas(canvas,i)
{
	var cat = loaded_images[i];
		
		var ndim = scale(cat.width,cat.height,$('#burns-home'));
		var current_canvas = canvas.get(0);
		
		current_canvas.width = ndim.w;
		current_canvas.height = ndim.h;
		
		canvas.css({
			marginLeft:	ndim.ml+'px',
			marginTop:	ndim.mt+'px'
		});
		
		var context = current_canvas.getContext("2d");
		context.drawImage(cat, 0,0,ndim.w,ndim.h);
	
	if(first){
		$('#bh-canvas-current').animate({ 'opacity':1 });
		setSlides();
		first = false;
	}
	if(clicked){
		this_canvas.fadeIn(1000);
		timer = setInterval('nextSlide()',slideDuration);
		clicked = false;
	}
}

function setSlides()
{
    this_canvas.animate({opacity: 1.0}, fadeDuration);
    timer = setInterval('nextSlide()',slideDuration);
}

function nextSlide()
{
	nextIndex = currentIndex+1;
    
    if(nextIndex >= loaded_images.length){
		nextIndex = 0;
    }
    
    next = this_canvas.attr('id') == 'bh-canvas-current' ? $('#bh-canvas-next') : $('#bh-canvas-current');
	
	drawToCanvas(next,nextIndex);
	next.animate({opacity: 1.0}, fadeDuration);
	this_canvas.animate({opacity: 0.0}, fadeDuration);
	
	this_canvas = next;
	currentIndex = nextIndex;
}

function bgThumbClick(n)
{
	clearInterval(timer);
	this_canvas.fadeOut(1000,function(){
		drawToCanvas(this_canvas,n);
		currentIndex = n;
	});
}

function resizeTimer()
{
	clearTimeout(rt);
	if( mc == "home"){
		rt = setTimeout("burnsWindow()", 100);
	}else if( mc == "collections"){
		rt = setTimeout("resizeCollections()", 100);
	}else if( mc == "cart"){
		rt = setTimeout("resizeCart()", 100);
	}else if( mc == "shirt"){
		rt = setTimeout("resizeShirt()", 100);
	}else if( mc == "press"){
		rt = setTimeout("resizePress()", 100);
	}else if( mc == "contact"){
		rt = setTimeout("resizeContact()", 100);
	}else if( mc == "checkout"){
		rt = setTimeout("resizeCheckout()", 100);
	}
}

function burnsWindow()
{
	var cbw = $('#burns-home').width();
	var cbh = $('#burns-home').height();
	var bc = 54;
	
	var nh = $(window).height() - $('#navigation').height() - bc;	
	var nw = $(window).width() - bc;	
	var nlm = (-1*(nw+bc-18))/2;
	var ntm = (-1*(nh+$('#navigation').height()+bc))/2;
	
	$('#burns-home').animate({
		height:			nh+'px',
		width:			nw+'px',
		marginLeft:		nlm+'px',
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic',function(){
		if(!first)
			drawToCanvas(this_canvas,currentIndex);
	});
}


function setupPress()
{
	$('a.lb').prettyPhoto({ theme:'dark_rounded' });	
}

function setupCollections()
{
	$('#collection-name').hide();
	$('#collection-name').fadeIn(2000);
	$('#back').click(function(){ bringBack(); });
	
	$('.photo', '.product').hide();
	$('.product').prepend('<div class="loader-box"><img src="images/layout/loader.gif" alt="Loading" class="loader-icon" /></div>');
	
	lt = setInterval("imageLoaded()",200);
}

function imageLoaded()
{
	$('.photo', '.product').each(function(i,e){
		db.append($(e).width());
		if( $(e).width() > 0 && $(e).siblings('.loader-box').length > 0 ){
			//db.append($(e).attr('alt'));
			$(e).siblings('.loader-box').remove();
			$(e).fadeIn(1000);
			if( $(e).parent().find('img').attr('alt') == '200TC' ){
				var par = $(e).parent();
				clickProduct(par.find('img').attr('src'), par, $('.product').index(par));
			}else{
				$(e).parent().click(function(){ 
					db.html("Clicked Index: "+$('.product').index($(this))); 
					clickProduct($(this).find('img').attr('src'), $(this), $('.product').index($(this)));
				});
			}
			li++;
		}
	})
	
	if( li >= $('.photo', '.product').length ){
		clearInterval(lt);
	}
}

function setupBrowser(w)
{	
	$('#left-arrow').click(function(){newMoveBrowser('l'); /*moveBrowser('l');*/});
	$('#right-arrow').click(function(){newMoveBrowser('r');/* moveBrowser('r');*/ });
	
	win = $(window);
	if( w == 'c' ){
		pp	= $('.product-previews');
		var _a = ($('.product').length*271.7);
		mm = 95;
	}else if( w == 'p' ){
		pp	= $('.press-content');
		var _a = ($('.gallery-item').length*240);
		mm = 30;
	}
	
	var _x = (_a/win.width());
	var _y = _x*win.width();
	var _z = _y-_a;
	
	pp.width(_a);
	win.resize(function(){ resizeBrowser(); })		
	getStops();
}

function resizeCart()
{
	var bc = 54;
	
	var ch = $('#cart-view').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	$('#cart-view').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}

function resizeCheckout()
{
	var bc = 54;
	
	var ch = $('#checkout-view').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	$('#checkout-view').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}

function resizeShirt()
{
	var bc = 54;
	
	var ch = $('#shirt-container').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	$('#shirt-container').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}

function resizePress()
{
	var bc = 54;
	
	var ch = $('#press-container').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	$('#press-container').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}


function resizeCollections()
{
	var bc = 54;
	
	var ch = $('#collections-container').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	var dh = $(document).height();
	
	$('#collections-container').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}

function resizeContact()
{
	var bc = 54;
	
	var ch = $('.contact-view').height();
	var ntm = (-1*(ch+$('#navigation').height()+bc))/2;
	
	$('.contact-view').animate({
		marginTop:		ntm+'px'
	}, 200, 'easeOutCubic');
}

function newMoveBrowser(d)
{
	var product_previews_width = q = pp.width();
	var current_left_margin = x = Math.abs(parseInt(pp.css('margin-left')));
	var window_width = y = win.width();
	var remaining = z = q-y-x;
	
	if( d == 'r' ){
		if( remaining >= window_width ){
			pp.animate({ 
				"margin-left":(-1*(current_left_margin)-window_width)+'px'
			}, 600, 'easeInOutCubic');
		}else{
			pp.animate({ 
				"margin-left":(-1*(current_left_margin)-remaining)+'px'
			}, 600, 'easeInOutCubic');
		}
	}else{
		if( current_left_margin >= window_width ){
			pp.animate({ 
				"margin-left":(-1*(current_left_margin)+window_width)+'px'
			}, 600, 'easeInOutCubic');
		}else{
			pp.animate({ 
				"margin-left":'0px'
			}, 600, 'easeInOutCubic');
		}
	}
}

function moveBrowser(dir)
{		
	var np;

	if( dir == "r" && stop < stops ){
		stop++;
		np = win.width()*(-1*(stop-1))+mm;
		pp.animate({ 
		"margin-left":np+'px'
		}, 600, 'easeInOutCubic');
	}else if( dir == "l" && stop > 2 ){
		stop--;
		np = win.width()*(-1*(stop-1))+mm;
		pp.animate({ 
		"margin-left":np+'px'
		}, 600, 'easeInOutCubic');
	}else if( dir == "l" && stop == 2 ){
		stop--;
		np = win.width()*(-1*(stop-1));
		pp.animate({ 
		"margin-left":'0px'
		}, 600, 'easeInOutCubic');
	}
	
	db.html("Stop: " + stop + "<br />Of: " + stops + "<br />Moving: " + dir);
}

function getStops()
{
	stops = Math.ceil(pp.width()/$(window).width());
}

function resizeBrowser()
{
	/*var ns = Math.ceil(pp.width()/$(window).width());
	
	stops = ns;	
	db.html("Stops: " + stops + "<br/>" + "Stop: " + stop);*/
}

function clickProduct(p, cur, j)
{
	$('#left-arrow').fadeOut(500);
	$('#right-arrow').fadeOut(500);
	
	var fs = p.split("masked/");
	var ss = fs[1].split(".");
	var ns = fs[0] + "large/" + ss[0] + ".jpg";
	var ls = fs[0] + "large/thumbs/" + ss[0] + "-thumb.jpg";
	var cs = fs[0] + "collar/thumbs/" + ss[0] + "-collar-thumb.jpg";
	var cu = fs[0] + "cuff/thumbs/" + ss[0] + "-cuff-thumb.jpg";
	
	var diff_pre = -400;
	var diff_post = $('.product-previews').width();
	
	$('.product').each(function(i,e){
		if( i < j ){
			$(e).animate({
				'margin-left':diff_pre+'px'
				}, 500, 'easeInSine');
		}else if( i > j ){
			$(e).animate({
				'margin-left':diff_post+'px'
				}, 500, 'easeInSine');
		}else{
			db.append("<br />Registered Index: "+i);
			productDisplay(e,i,ns,cs,ls,cu);
		}
	});
}

function productDisplay(e,i,ns,cs,ls,cu)
{	
	active = e;
	active_index = i;
	clone = $(e).clone(false);
	var w = $(e).offset();
	
	clone.css({ 'visibility':'hidden' });
	$(e).before(clone);
	$(e).wrap('<div class="product-display" />');
	$(e).css({ 'margin-left':'0px' });
	
	var pd = active_wrap = $('.product-display');
	pd.css({ 'left':w.left+'px' });
	pd.detach();
	
	$('#collections-browser').prepend(pd);
	
	pd.animate({
		'margin-left':-1*(pd.width()/2)+'px',
		'left':'50%'
	}, 500, 'linear',function(){ loadProduct(active,ns,cs,ls,cu); });

	
}

function loadProduct(a,ns,cs,ls,cu)
{
	$.get("includes/pages/product.php", { product:$(a).find('img').attr('alt') }, function(d){
			active_wrap.append(d);
			$('.product-content').fadeIn(500);
			setupZoom(ns,true);
			if( $('#collection-name').html().indexOf("200TC") == -1 ){
				$('#back').fadeIn(500);
			}
			var vs = cs.replace("-thumb", "");
			var bp = vs.replace("thumbs/", "");
			var cv = bp.replace("collar", "cuff");
			var cf = cv.replace("-collar", "-cuff");
			$('.collar-view').attr('src', cs).click(function(){ swapProductView(bp); });
			$('.cuff-view').attr('src', cu).click(function(){ swapProductView(cf); });
			$('.overview-view').attr('src', ls).click(function(){ swapProductView(ns); });
		});
}

function swapProductView(bp)
{
	$('.zoomer').fadeOut(500, function(){
		$('.zoom-slider').css({ 'bottom':'0px' });
		setupZoom(bp);	
	});
}


function bringBack()
{
	clone.remove();
	$(active).show();
	active_wrap.fadeOut(400);
	$('#back').fadeOut(500);
	$('#left-arrow').fadeIn(500);
	$('#right-arrow').fadeIn(500);
	
	collision_timer = setInterval(function(){ findIntersectors(active, '.product') }, 50);
	
	$('.product', '.product-previews').each(function(i,e){
		if( i == active_index-1 && active_index > 0 ){
			sib = e;
		}else if( i == active_index && active_index == 0 ){
			sib = e;
		}
		
		if( active_index != 0 && i == 0 ){
			$(e).animate({
				'margin-left':'0px'
				}, 500, 'easeOutSine');
		}else{
			$(e).animate({
				'margin-left':'-140px'
				}, 500, 'easeOutSine');
		}
	});	
}

function resetActive()
{
	$(active).detach();
	active_wrap.remove();
	if( active_index > 0 ){
		$(sib).after($(active));
		$(active).animate({
			'margin-left':'-140px'
			}, 200, 'easeOutSine');
	}else{
		$(sib).before($(active));
		$(active).animate({
			'margin-left':'0px'
			}, 200, 'easeOutSine');
	}
}

function findIntersectors(targetSelector, intersectorsSelector) {

    var $target = $(targetSelector);
    var tAxis = $target.offset();
    var t_x = [tAxis.left, tAxis.left + $target.outerWidth()];
    var t_y = [tAxis.top, tAxis.top + $target.outerHeight()];

    $(intersectorsSelector).each(function(i,e) {
          var $this = $(this);
          var thisPos = $this.offset();
          var i_x = [thisPos.left, thisPos.left + $this.outerWidth()]
          var i_y = [thisPos.top, thisPos.top + $this.outerHeight()];

          if ( t_x[0] < i_x[1] && t_x[1] > i_x[0] &&
               t_y[0] < i_y[1] && t_y[1] > i_y[0] && $(this).find('img').attr('alt') != $(active).find('img').attr('alt')) {
              resetActive();
              clearTimeout(collision_timer);
          }
    });
}

var dist;
var op;
var vo;
var offset;
var zoom_timer;

var cw;
var ch;
var zf;
var sw;
var sh;

var per;
var sx;
var sy;

function setupZoom(src,first){
	
	if( first ){
		$(active).hide();
	}
	
	$(ci).unbind();
	$('.zoom-slider').draggable("destroy");
	$('.zoom-slider').unbind();
	
	$(ci).remove();
	$(czw).html('<img src="" alt="" class="'+ci.replace(".","")+'" />');
	$(czw).append('<div class="loader-box"><img src="images/layout/loader.gif" alt="Loading" class="loader-icon" /></div>');
	$(ci).hide();
	$(ci).attr('src', '');
	$(ci).load(function(){
		cw = $(this).width();
		ch = $(this).height();
		zf = 4;
		$(this).fadeIn(500);
		$(this).siblings('.loader-box').remove();
		//$(active).hide(500);
	});
	
	$(ci).attr('src', src);
	
	$('.zoom-slider').draggable({ snap: true, containment: '.zoom-guide', scroll: false, axis: "y" });
	
	dist = parseInt($('.zoom-guide').css('height'));
	dist = dist - parseInt($('.zoom-slider').css('height'));
	
	$('.zoom-slider').mousedown(function(){
		zoom();
	});
	$('.zoom-slider').mouseup(function(){
		if( $(this).length ){
			re();
		}
	});
//	$('.zoom-slider').bind('taphold',function(){
//		zoom();
//	});
	$(document).mouseup(function(){
		if( $('.zoom-slider').length ){
			re();
		}
	});	
};

function zoom()
{
	zoom_timer = setInterval(function(){
		
		op = $('.zoom-slider').position();
		offset = dist - op.top;
		per = (offset/dist);
		sw = ((zf*per)*cw)+cw;
		vo = (sw/cw);
		
		$(ci).width(sw);
		sh = $(ci).height();
		
		$('.zoom-bounds').width(sw*2);
		$('.zoom-bounds').height(sh*2);
		
		
		var nx = (-1*(sw-cw))/2;
		var ny = (-1*(sh-ch))/2;
		
		
		$('.zoom-bounds').css({ 'left': (nx*2)+'px', 'top': (ny*2)+'px'});
		$(ci).css({ 'left': nx+'px', 'top': ny+'px'});
		
	}, 100);
}

function re()
{
	$('.zoom-slider').draggable("disable");
	clearInterval(zoom_timer);
	
	var o = $(cz).offset();
	
	$(ci).draggable("destroy");
	$(ci).draggable({ containment: [-1*(sw-cw)+o.left, -1*(sh-ch)+o.top, o.left, o.top], cursor: 'pointer', scroll: false, scrollSpeed: 80, scrollSensitivity: 80 });
	$('.zoom-slider').draggable("enable");
}

//Cart

simpleCart.checkoutTo = PayPal;
simpleCart.email = "roderick@rodericktung.com";
simpleCart.taxRate = 0.10;
simpleCart.shippingQuantityRate = 6.25;

function cartAdd(p,n)
{
	var q = $('.item_quantity').val();
	var s = $('.item_size').val();
	var t = $('.thumb').html();
		
	simpleCart.add('preview='+t , 'name='+p,'price='+n,'quantity='+q,'shipping=5.00', 'size='+s);
	window.location = "?l=cart";
}

function cartCopy()
{
	$('.shipping input',':visible').each(function(i) {                 
	    $(this).val( $('.billing input').eq(i).val() );
    });
	
	var b_country = $('.b_country').val();
	$('.s_country').selectOptions(b_country);
	
	var b_state = $('.b_state').val();
	$('.s_state').selectOptions(b_state);
}



function scale(iw,ih,$parent) {
        var imgW = iw,
            imgH = ih,
            destW = $parent.width(),
            destH = $parent.height(),
            ratioX, ratioY, ratio, newWidth, newHeight,borderW,borderH;
        
        
        // check for valid border values. IE takes in account border size when calculating width/height so just set to 0
        borderW = isNaN(borderW) ? 0 : borderW;
        borderH = isNaN(borderH) ? 0 : borderH;
        
        // calculate scale ratios
        ratioX = destW / imgW;
        ratioY = destH / imgH;
		
		ratio = ratioX < ratioY ? ratioX : ratioY;
        // Determine which algorithm to use
        /*if (opts.scale === "fit") {
        	ratio = ratioX > ratioY ? ratioX : ratioY;
            
        } else if (opts.scale === "fill") {
        borderW = parseInt($img.css("borderLeftWidth"), 10) + parseInt($img.css("borderRightWidth"), 10),
        borderH = parseInt($img.css("borderTopWidth"), 10) + parseInt($img.css("borderBottomWidth"), 10),
        
        */
        //}

        // calculate our new image dimensions
        newWidth = parseInt(imgW * ratio, 10) - borderW;
        newHeight = parseInt(imgH * ratio, 10) - borderH;
        
        // Set new dimensions to both css and img's attributes
       /* $img.css({
            "width": newWidth,
            "height": newHeight
        }).attr({
            "width": newWidth,
            "height": newHeight
        }); */
        
        var ml = Math.floor((destW - newWidth) / 2);
        var mt = Math.floor((destH - newHeight) / 2);
        
        return { w:newWidth, h:newHeight, ml:ml, mt:mt };
    }

    /**
     * To calculate the correct scale ratio, we need the image's original size rather than some preset values,
     * which were set either manually in code or automatically by browser.
     * Thanks FDisk for the solution:
     * http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
     */
    function getOriginalImgSize($img) {
        var t = new Image();
        t.src = $img.attr("src");
        return {width: t.width, height: t.height};
    }
    
    /**
     * If the element is invisible, jQeury .height() and .width() return 0 in IE.
     * This function returns the hidden element's correct width and height.
     * Thanks elliotlarson for the solution:
     * http://stackoverflow.com/questions/2345784/jquery-get-height-of-hidden-element-in-jquery-1-4-2
     */
    function getHiddenElemSize(element) {
        var copy = element.clone().css({visibility: 'hidden', display: 'block', position: 'absolute'});
        $("body").append(copy);
        var size = {width: copy.width(), height: copy.height()};
        copy.remove();
        return size;
    }
    
    function getBaseURL() {
        var url = location.href;  // entire url including querystring - also: window.location.href;
        var baseURL = url.substring(0, url.indexOf('/', 14));
    
    
        if (baseURL.indexOf('http://localhost') != -1) {
            // Base Url for localhost
            var url = location.href;  // window.location.href;
            var pathname = location.pathname;  // window.location.pathname;
            var index1 = url.indexOf(pathname);
            var index2 = url.indexOf("/", index1 + 1);
            var baseLocalUrl = url.substr(0, index2);
    
            return baseLocalUrl + "/";
        }
        else {
            // Root Url for domain name
            return baseURL + "/";
        }
    
    }

function popUp(URL)
{
	eval(window.open(URL, 'popUpWindow', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=0,width=640,height=360,left = 220,top = 100'));
};

































