//	jQuery Largebox plugin
//	.based on jQuery lightbox plugin by Benjamin "balupton" Lupton {http://www.balupton.com}
//	.modified and tailored by Story Worldwide

(function($jq){
	
	$jq.LargeboxClass = function () {
		this.construct();
	};
	
	$jq.fn.largebox =  function( params ) {
		$jq.Largebox = $jq.Largebox || new $jq.LargeboxClass();
		var defaults = {
			top:		100, 	// distance from top of page
			width: 		350,	// width of box															CHANGED
			height: 	530,	// height of box
			type:		'html', // default type
			opacity: 	0.3,	// opacity value
			stripAt: 	'body', // when parsing a html document via AJAX this is the tag that wraps the content to display in the box 
			events: 	true,
			border:		5,
			method:   'GET'
		};
		params = $jq.extend(defaults,params);
		$jq.Largebox.populateParams(params);
		if (params.events) {
            $jq(this).click(function() {
                var hrefdata = $jq(this).attr('href');    // store the href data in a temporary variable
                             	
                if ($jq('.radioselector:checked').length>0) {    // do we have any selected from elements with the .radioselector class        
       
       							var boxSel = $jq('.radioselector:checked');
       							
       							if(!hrefdata){             		
		              		var prodObj = $jq('#' + boxSel.attr('name') + '-qty-add-common');
		              		var skuObj = $jq("input[@type=hidden][@name='" + boxSel.val() + "']");
											var checkedVal = '&' + prodObj.attr('name') + '=' + prodObj.val() + '&skuId=' + skuObj.val();
		              		var hrefdata = $jq('#url').val() + checkedVal;
		              	}
       
                    if (hrefdata.indexOf('?')>0) {
                    	hrefdata = hrefdata + '&' + boxSel.attr('name') + "=" + $jq('.radioselector:checked').val();    // add the data from the radiobuttons to the querystring
                    }else{ 
                    	hrefdata = hrefdata + '?' + $jq('.radioselector:checked').val();    // or create a querystring with data from teh radiobuttons
                    }
                }
                
                if(!hrefdata){             		
              		var fmData = $jq('#fmName').serialize();
              		var hrefdata = $jq('#url').val() + "&" + fmData;
              	}
              	
                if (!$jq.Largebox.start(hrefdata)) return true;    // supply the variable hrefdata to the start() function instead
                //    Largebox will load the href of it's assigned tag into itself
                return false;
            })
        }

	};

	$jq.extend($jq.LargeboxClass.prototype,{
		top:		null,
		width: 		null,
		height: 	null,
		padding: 	null,
		type: 		null,
		opacity: 	null,
		stripAt: 	null,
		border:	 	null,
		method:		null,
		speed: 		400,
		construct: function () {
			return true;
		},
		tree: null,
		populateParams: function (params) {
			$jq.Largebox.top = 			params.top;
			$jq.Largebox.width = 		params.width;
			$jq.Largebox.height = 		params.height;
			$jq.Largebox.opacity = 		params.opacity;
			$jq.Largebox.type = 		params.type;
			$jq.Largebox.stripAt =		params.stripAt;
			$jq.Largebox.border =		params.border;
			$jq.Largebox.method =		params.method;
		},
		start: function (target) {
			$jq('embed, object, select').css('visibility', 'hidden');//.hide(); - don't use
			var tree = null;
			switch($jq.Largebox.type) {
				case 'html':
								
				$jq.Largebox.clearDOM(tree);
				  
				$jq.ajax({
					type: $jq.Largebox.method,
					url: target,
					success: function (data) {
						//	what to do with data from the ajax call
						tree = $jq.Largebox.parseDocument(data);
						$jq.Largebox.appendDOM(tree);
						$jq('#shopBagValue').html('(' + $jq('#basketTotalItems').val() + ')');
					},
					error: function(res) {
						//console.log(res);  
					}
				})
				break;
				case 'htmlNoBasket':
								
				$jq.Largebox.clearDOM(tree);
				  
				$jq.ajax({
					type: $jq.Largebox.method,
					url: target,
					success: function (data) {
						//	what to do with data from the ajax call
						tree = $jq.Largebox.parseDocument(data);
						$jq.Largebox.appendDOM(tree);
					},
					error: function(res) {
						//console.log(res);  
					}
				})
				break;
				case 'image':
					$jq.Largebox.clearDOM(tree);
				
					tree = $jq('<img alt="" title="" src="'+target+'" />');
					$jq.Largebox.appendDOM(tree);
				break;
			}
			return true;
		},
		parseDocument: function (data) {
			//	finds where to fetch html from, omitting the head and html tags
			var start, end;
			if ($jq.Largebox.stripAt != 'body') {
				return $jq(data).find($jq.Largebox.stripAt).children();
			} else {
				start = data.indexOf('<body>')+6;
				end = data.indexOf('</body>')
				if(start>-1 && (end>-1 && end>start)){
					return data.substring(start,end);
				} else return 'Document is not valid XHTML';
			}
		},
		clearDOM: function(tree){
			$jq('embed, object, select').css({ 'visibility' : 'visible' });//.show();
			$jq('#largebox-overlay').remove();
			$jq('#largebox').remove();
			var overlay = $jq('<div id="largebox-overlay"></div>');
			var thebox = $jq('<div id="largebox"></div>');
			var close_button = $jq('<div id="largebox-close"></div>');
			$jq(thebox).css('width',$jq.Largebox.width+'px').css('top',$jq.Largebox.top+'px').hide();			//	removed the fixed height!
			$jq('body').append($jq(overlay));
			$jq('body').append($jq(thebox));
			//	click anywhere on the overlay to close the box
			$jq(overlay).unbind().click(function() {
				$jq.Largebox.finish();
				return false;	
			});
			//	close button
			$jq(thebox).append($jq(close_button));
			$jq(close_button).click(function (){
				$jq.Largebox.finish();
			});		
			$jq.Largebox.resizeOverlay();
			$jq.Largebox.repositionBox();
			$jq(overlay).css('opacity',$jq.Largebox.opacity).fadeIn(400, function(){
				if(tree)
				{
					$jq(thebox).append($jq(tree)).fadeIn(300);
				}
				else
				{
				  var mar_tb =  ($jq.Largebox.height - 32) / 2;
				  var mar_rl =  ($jq.Largebox.width - 32) / 2;
				  var margin = 'margin:' + mar_tb + 'px ' + mar_rl + 'px ' + mar_tb + 'px ' + mar_rl + 'px;';
					$jq(thebox).append('<div style="' + margin + ' width: 32px; height:32px;"><img src="/images/ajax-loader.gif" height="32" width="32" /></div>').fadeIn(300);
				}
			});
			//	if there is an element with the id close_box, assign a closing function to it
			if ($jq('#close_box')!=null) {
				$jq('#close_box').unbind().click(function() {
					$jq.Largebox.finish();
					return false;	
				});
			}
		},
		appendDOM: function(tree) {
			//console.log(tree);
			//																										ADDED 090908 WB
			$jq.Largebox.clearDOM(tree);
			//																										ADDED 310708	
			//	hide the update panel if there is one
			if ($jq('.update_box')!=null) {
				$jq('.update_box').hide();
			}
			//	if there is an element with the id update_total, assign an update function to it
			if ($jq('#update_total')!=null) {
				$jq('#update_total').unbind().click(function() {
					// AJAX call to update the basket and return the new total
					var updateUrl = $jq('#basketUpdateUrl').val();
					var searchVal = updateUrl.search(/=&/)
					if(searchVal >= 0)
					{
						
						updateUrl = updateUrl.replace(/=&/,"=" + $jq('#basketQty').val() + "&");
					}
					else
					{
						updateUrl += '' + $jq('#basketQty').val();
					}
					
					var tree = null;
					$jq.Largebox.clearDOM(tree);
					
					$jq.ajax({
						type: "GET",
						url: updateUrl,
						success: function (data) {
							//	what to do with data from the ajax call
							switch($jq.Largebox.type) {
								case 'html':
								tree = $jq.Largebox.parseDocument(data);
								break;
							}

							/*$jq('embed, object, select').css({ 'visibility' : 'visible' });//.show();
							$jq('#largebox-overlay').remove();
							$jq('#largebox').remove();*/
							
							$jq.Largebox.appendDOM(tree);
							$jq('#shopBagValue').html('(' + $jq('#basketTotalItems').val() + ')');


						},
						error: function(res) {
							//console.log(res);
						}
					})
					//$jq.Largebox.alertQuantityChange('reset');
					return false;	
				});
			}
			//																										MODIFIED 310708
			//	if the parsed document has buttons for quantity, assign that functionality
			if ($jq('.qtyadd')!=null) {
    			 $jq('.qtyadd').click(function () {
			     	var i = $jq(this).parent('div').children('input').val();
			     	if( i < 4 ) i++;
			     	$jq(this).parent('div').children('input').val(i);
			     	if ($jq('.update_box')) $jq.Largebox.alertQuantityChange();
			     	return false;
			     });
			     $jq('.qtysub').click(function () {
			     	var i = $jq(this).parent('div').children('input').val();
			     	if (i!=1) {
				     	i--;
				     	$jq(this).parent('div').children('input').val(i);
				     	if ($jq('.update_box')) $jq.Largebox.alertQuantityChange();
			     	}
			     	return false;
			     });
			 } 
			//	handles specific basket delete functionality
			if ($jq('.basket_delete')!=null) {
				$jq('.basket_delete').click(function () {
					//	Add AJAX logic to delete an item from basket here
				});
			}
			//																										ADDED 250708	
			//	when a size is selected from the size pre-selection
			if ($jq('#btn_confirm')!=null) {
				$jq('#btn_confirm').unbind().click(function() {
					
					//	target value passed to the minibasket should now include the value of either $jq('size_1') or $jq('size_2') depending on which was selected
					//	might need some validation on that, to see if $jq('size') has a value 

					//var checkedVal = $jq("input[@type=radio][@class='radioselector'][@checked]").val();
					var checkedObj = $jq("input[@type=radio][@class='radioselector'][@checked]");

					if(checkedObj){
						var skuObj = $jq("input[@type=hidden][@name='" + checkedObj.val() + "']");
						var prodObj = $jq('#' + checkedObj.attr('name') + '-qty-add-common');
						var checkedVal = checkedObj.attr('name') + '=' + checkedObj.val() + '&' + prodObj.attr('name') + '=' + prodObj.val() + '&skuId=' + skuObj.val();
						var returnUrl = $jq('#basketReturnUrl').val();
						$jq.Largebox.finish();
						$jq.Largebox.start( '/altercart/templates/transaction/minibag.tmpl?' + checkedVal + '&returnurl=' + returnUrl);
						return false;	
					}
					return false;	
				});
			}
			if ($jq('#cancel_item')!=null) {
				$jq('#cancel_item').unbind().click(function() {
					//	delete the just-added item from bag and return
					$jq.ajax({
						type: "GET",
						url: $jq('#basketDeleteUrl').val(),
						success: function (data) {
							var tree = null;
							//	what to do with data from the ajax call
							$jq('#shopBagValue').html('(' + data + ')');
							switch($jq.Largebox.type) {
								case 'html':
								tree = $jq.Largebox.parseDocument(data);
								break;
							}
						}
					})
					$jq.Largebox.finish();
					return false;
				});
			}
			if ($jq('#view_bag')!=null) {
				$jq('#view_bag').unbind().click(function() {
					location.href=$jq('#basketReturnUrl').val();
					$jq.Largebox.finish();
					//	go to shopping bag
					return false;	
				});
			}
			
			if($jq('#coremetrics_continue') !=null){
			      $jq('#coremetrics_continue').click(function (){
                var ac = $jq("input[name='action']:checked").val(); 
                var destination = '';   
                
                switch(ac)
                {
                    case "anonymous":
                        destination="http://data.coremetrics.com/privacy/anonymous.html";
                        break;
                    case "opt_out":
                        destination="http://data.coremetrics.com/privacy/optout.html";
                        break;
                    case "opt_in":
                        destination="http://data.coremetrics.com/privacy/cancel.html";
                        break;
                }
                newWindow=window.open ("http://data.coremetrics.com/privacy/privacy_handler.php"+"?dest=" + destination + "&act=" + ac,"popup1", "resizeable,width=400,height=400"); 
            });
			}
			
			if($jq('#coremetrics_cancel') !=null){
			      $jq('#coremetrics_cancel').click(function (){
                $jq.Largebox.finish();
            });
			}
			
			if($jq('#coremetrics_status') !=null){
			      $jq('#coremetrics_status').click(function (){
                var bg_color="#ffffff";
                var bg_img="";
                window.open("http://data.coremetrics.com/privacy/getStatus.php" + "?bg=" + bg_color + "&im=" + bg_img, "cmstatus","resizeable,width=400,height=300")
                return false;
            });
			}
			//																										END ADDED
			$jq(window).resize(function () { $jq.Largebox.resizeOverlay(); $jq.Largebox.repositionBox(); });
			$jq(window).scroll(function () { $jq.Largebox.repositionBox(); });
		},
		//																											ADDED 250708	
		alertQuantityChange: function (param) {
			//	swaps text panels when quantity is changed
			switch (param) {
				case 'reset':
					if ($jq('.update_box') && $jq('.summary_box'))	{
						$jq('.update_box').hide();
						$jq('.summary_box').fadeIn("1000");
					}
				break;
				default:
					if ($jq('.update_box'))	{
						$jq('.summary_box').hide();
						$jq('.update_box').fadeIn("1000");
					}
				break;
			}
		},
		resizeOverlay: function ( ) {
			$jq('#largebox-overlay').css({
				width:		$jq(window).outerwidth,
				height:		$jq(window).outerheight
			});
			//	ie6...
			if (document.documentElement) $jq('#largebox-overlay').css('height','2000px');
		},
		repositionBox: function ( )		{		
			// Get page scroll
			var pageScroll = this.getPageScroll();
			
			var nTop = pageScroll.yScroll + $jq.Largebox.top;
			var nLeft = Math.round(($jq(document).width()/2))-Math.round($jq.Largebox.width/2);	
		
			var outercss = {
				left: 0,
				top: pageScroll.yScroll
			};
			
			var innercss = {
				left: nLeft,
				top: nTop
			};
			
			$jq('#largebox').css(innercss);
			$jq('#largebox-overlay').css(outercss);
		},
		getPageScroll: function ( ) {
			var xScroll, yScroll;
			if (self.pageYOffset)
			{	// Some browser
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop)
			{	// Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body)
			{	// All other browsers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
			return arrayPageScroll;
		},
		finish: function ( )
		{	
			$jq('#largebox').hide();
			$jq('embed, object, select').css({ 'visibility' : 'visible' });//.show();
			$jq('#largebox-overlay').remove();
			$jq('#largebox').remove();
		}
	})
	
	$jq(function() {
		$jq.Largebox = $jq.Largebox || new $jq.LargeboxClass();
	});

})(jQuery);

