var site_url = 'http://'+window.location.host+'/';
var randNum = Math.floor((Math.random()*1000000)+1);
var randVal = "?cval="+randNum.toString();

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

function create_declaration_wrapper(declaration_text, image_url, user_name, updated, user_id, shared) {
	var wrapperHtml = '';
	var shareText = (user_id == '') ? '' : 'promotions/aooak/share/'+user_id;
	
	var iFrameHtml = '<iframe \
				src="http://www.facebook.com/plugins/like.php?href='+site_url+shareText+'&amp;layout=button_count&amp;show_faces=false&amp;width=95&amp;action=like&amp;colorscheme=light&amp;height=21" \
				scrolling="no" \
				frameborder="0" \
				style="border:none; overflow:hidden; width:95px; position: absolute; height:21px;" \
				allowTransparency="true">\
				</iframe>';
	var fbXhtml = '<div id="fb-root"></div><script> \
						(function(d, s, id) { \
					  		var js, fjs = d.getElementsByTagName(s)[0]; \
					  		if (d.getElementById(id)) return; \
					  		js = d.createElement(s); js.id = id; \
					  		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; \
					  		fjs.parentNode.insertBefore(js, fjs); \
						}(document, "script", "facebook-jssdk")); \
					</script> \
					\
				 <div class="fb-like" data-href="'+site_url+shareText+'" data-send="false" data-layout="button_count" data-show-faces="false"></div> \
				';
	wrapperHtml = '<script>$("#declaration").bigtext({maxfontsize: 100, minfontsize: 20});</script><div id="declaration_wrapper"> \
					<a class="close" href="#" onclick="aooak.close_overlay(); return false;">close</a> \
					<div id="declarationBody"> \
						<div id="declaration" class="declareText tilt02">I\'m a<div>'+declaration_text+'</div> </div> \
						<div id="declaration_user"> \
							<h2 class="userName">'+user_name+'</h2> \
							<div class="declareShare_btns"> \
								<div class="fb-like">'+iFrameHtml +'</div> \
								<div class="declareTweet_btn"><script charset="utf-8" src="//platform.twitter.com/widgets.js" type="text/javascript"></script> \
								<a href="https://twitter.com/share?url=http://www.drpepper.com/promotions/aooak/share/'+user_id+'" class="twitter-share-button" data-text="Every Pepper drinker is unique. '+user_name+' just declared. What\'s yours? #ImA" data-count="horizontal">Tweet</a></div> \
							</div> \
						</div> \
					</div> \
				</div>';
    if(shared==undefined){
        wrapperHtml += '<script>FB.XFBML.parse();</script>';
    }
 //FB.XFBML.parse();
 return wrapperHtml; 			
}   

function commercial_facebook_link() {
	
	var returnHtml = '';
	
	returnHtml = '<script> \
						(function(d, s, id) { \
					  		var js, fjs = d.getElementsByTagName(s)[0]; \
					  		if (d.getElementById(id)) return; \
					  		js = d.createElement(s); js.id = id; \
					  		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; \
					  		fjs.parentNode.insertBefore(js, fjs); \
						}(document, "script", "facebook-jssdk")); \
					</script> \
					\
					<div class="fb-like" data-href="http://www.youtube.com/watch?v=02vku-6fZWQ" data-send="false" data-layout="button_count" data-show-faces="false"></div> \
					\
					';
 return returnHtml; 				
}

function collapseProfile() {
	//return; // do nothing when flash calls this function
    if($('#declareContainer').height()<55){
        $('#declareContainer h1').click();
    }

    if($('#aooak_center').height()<55){
        $('a.collapseProfile').click();
    }

}

$(document).ready(function(){
    aooak.init();
	
	//sets the declaration overlay to be the height of the screen
	$('#overlayDeclaration').height($('#overlayDeclaration').height() + 180);

	$('#overlayDeclaration_bg').live('click', function(){
		$('#overlayDeclaration').fadeOut('fast');
	});
	
	$('.viewDeclaration a').live('click',function(){
		getFlashMovie("mosaicSWF").showProfilePic($(this).attr('data-src'), $(this).attr('data-name'),$('#userDeclare_text div').text(), $(this).attr('data-updated'), $(this).attr('data-id'));
		return false;
	});
	
	//collapse the initial declaration window
	$('a.collapse').live('click', function(){
        if($(this).hasClass('selected')){
            $('#declareContainer h1').click();
        } else {
            $('.collapse').addClass('selected');
            $('#declareContainer').html('<h1 class="declareCollapse">MAKE YOUR DECLARATION</h1>');
            $('#declareContainer').animate({
                height: '30px'
            });
        }

	});
	//open initial declaration window
	$('#declareContainer h1').live('click', function(){
		$('.collapse').removeClass('selected');
		$('#declareContainer').animate({
			height: '594px'
		}, function(){
			$('#declareContainer').load(aooak.ajaxPath+'modal/_center/');
		});
		return false;
	});
	
	//collapse the profile window
	$('a.collapseProfile').live('click', function(){
        if($('#profileContainer').height()>50){
            $('#moduleContent').load(aooak.ajaxPath+'modal/profile_collapse/'+randVal);
            $('#profileContainer').animate({
                height: '50px'
            });
        } else {
            $('#profileContainer').animate({
                height: '430px'
            }, function(){
                $('#moduleContent').load(aooak.ajaxPath+'modal/profile_home/'+randVal);
            });
        }

		return false;
	});
	//open profile window
	$('#profile_collapse_wrapper').live('click', function(){
		$('#profileContainer').animate({
			height: '430px'
		}, function(){
			$('#moduleContent').load(aooak.ajaxPath+'modal/profile_home/'+randVal, function() {
				var text_to_fix = $('#userDeclare_text');
				text_to_fix.css('font-size','23px');
			});
		});
		return false;
	});
	
    $('#declare_submit a').live('click', submitDeclaration);
	
	
	$('.jtextfill').textfill({ maxFontPixels: 15 });
	
	$('#name').live('keyup',function() {
		$('.dyntextval').html(this.value);
		$('.jtextfill').textfill({ maxFontPixels: 24 });
	});
	
	// evalutate to see if user is signed in
	if($.cookie('drpepper_user') == null) {
		$('.makeDeclaration').css('display', 'block');
		$('.loggedIn').css('display', 'none');
	}else{
		$('.makeDeclaration').css('display', 'none');
		$('.loggedIn').css('display', 'block');
	};
	// open the video overlay
	$('a.watch_video').live('click', function(){
		$('#overlayCommercial_content').load(aooak.ajaxPath+'modal/_commercial/', function(){
			$('#overlayCommercial').fadeIn('fast');
			// _gaq.push(['_setAccount', gaAccount]);
			// _gaq.push(['_trackEvent','Commercial','View']);
			_gaq.push(['_trackPageview','/promotions/aooak/commercial']);
		});
		
	});
	// close commercial overlay
	$('a.commercialOverlay').live('click', function(){
		$('#overlayCommercial').fadeOut('fast');
		$('#DR_commercial').detach();
	});
	// places the footer at a set height from the top,
	// unless the user has a real tall window
	//if($(window).height() >= 1150){
	//	$('#footer-area').addClass('footer-areaFlex');
	//	$('#footer-area').removeClass('footer-areaStatic');
	//}else {
	//	$('#footer-area').removeClass('footer-areaFlex');
	//	$('#footer-area').addClass('footer-areaStatic');
	//};
	
});
$(window).resize(function(){
	if($(window).height() >= 1150){
		$('#footer-area').addClass('footer-areaFlex');
		$('#footer-area').removeClass('footer-areaStatic');
	}else {
		$('#footer-area').removeClass('footer-areaFlex');
		$('#footer-area').addClass('footer-areaStatic');
	};
})

aooak = {
	
	ajaxPath : (window.location.pathname == "/") ? "promotions/aooak/" : '',
	dec_text : '',
    userId:0,
	cookieName: 'drpepper_declaration',
	
    init:function(){
		if (location.hostname == "app.drpepper.com") { 
			this.ajaxPath = '/aooak/promotions/aooak/';
		} else if (location.hostname.indexOf('dpsg.codeandtheory.net') > -1 && location.hostname.indexOf('app') > -1) {
			this.ajaxPath = '/aooak/promotions/aooak/';
		} 
		
		if(window.location.pathname == "/promotions/") {
			this.ajaxPath = "aooak/";
		}
		
		if(window.location.pathname.indexOf('aooak/share') > -1) {
			this.ajaxPath = "/promotions/aooak/";
		}
		
        /*
        $('.buyShirt_body #buynow').live('click', function(){
        	//set the size
        	var size = $("select#sizes option:selected").text();
        	shirt_builder.set_size(size);
        	shirt_builder.build_checkout_url();
        	
        	var checkout_url = shirt_builder.get_checkout_url();
        	$('#buy_shirt').html("<a class='close' href='#' onclick='aooak.close_overlay(); return false;'>close</a><iframe src='"+checkout_url+"' width='100%' height='100%'></iframe>");
        	return false;
        });*/
        
    },
	
	pick_your_declaration:function(user_id, prev_dec){
		// previous declarations only exist for users who have declared after a janrain login on the site before
		if(prev_dec == undefined) {
			$('#overlay_content').load(aooak.ajaxPath+'modal/two_declares/?fbid='+user_id);
		} else {
			$('#overlay_content').load(aooak.ajaxPath+'modal/two_declares/?fbid='+user_id+'&prev_dec='+prev_dec);
		}
		$('#overlay').fadeIn();
		return false;
	},

	set_declare_text:function(string) {
        $.get(aooak.ajaxPath+'modal/profile_home/', function(data){
            $('#moduleContent').html(data);
        });
	},

    do_declare:function(string, edit){
        if(edit!=undefined){
          //  location.reload(true);
          $('.centerContainer').load(aooak.ajaxPath+'modal/profile_home/'+randVal);
          //if($('#twoDeclares') && !$('#profile')) {
			  return false; 
          /*} else {
			  this.close_overlay();
          }*/
        }
        return false;
    },

	submit_declare:function(decText, checkAgreed) {
        if(decText != '' && decText != "(30 character limit)") {
			aooak.check_profanity(decText, checkAgreed, function(){
				$.cookie(aooak.cookieName,base64.encode(decText), {expires:7, path: '/'});
				if($.cookie('drpepper_user') == null) {
                    $('#aooak_nav li.makeDeclaration a.captureIframe').click();
				} else {
                    // var success = aooak.do_declare(decText, true);
					aooak.set_declare_text(decText);
					aooak.close_overlay();
					getFlashMovie("mosaicSWF").showProfilePic($('.profile_avatar img').attr('src'), $('.userInfo .userName p').text(),decText, $('.viewDeclaration a').attr('data-updated'), $('.viewDeclaration a').attr('data-id'));
					
				}
			});
		}
	},

	check_profanity:function(string, checkAgreed, function_to_run){
		// before checking profanity, check if user has agreed to the rules
		
	
		var agreed = ($('#agreement').attr('checked') == 'checked'); 
		if(checkAgreed && agreed == false){
			$('.profanity-errors-container').html('<p>error:please agree to our simple rules</p>');
			$('.profanity-errors-container').show();
			$('#name').addClass('error');
		}else{
			// Check the string for profanity.  If the string is clean, run the function and return its value, otherwise return false.
			$.get(aooak.ajaxPath+'request/do_declare/'+encodeURIComponent(escape(string))+'/', function(data){
            	if(data == 'profanity'){
            		var errors = {
            		"1": "Sorry. No profanity please. Try again.",
					"2": "Oh my! Do you kiss your mother with that mouth? Try again.",
					"3":"Keep it clean please.",
					"4":"Now that wasn’t nice. Try again.",
					"5":"Curse words are a no go. Keep it sweet."
            		};
            		var errorNum = Math.floor((Math.random()*5)+1);
            		var errIndex = errorNum.toString();
					$('.profanity-errors-container').html('<p>'+errors[errIndex]+'</p>');
                	$('.profanity-errors-container').show();
        			$('#name').addClass('error');
                	return false;
				} else {
					return function_to_run();
				}
			});
		};
	},

    do_signin:function(){
		alert('yo!');
        $.get(aooak.ajaxPath+'modal/profile_home/', function(data){
            $('#declareContainer').html(data);
        });
		$('.makeDeclaration').css('display', 'none');
		$('.loggedIn').css('display', 'block');
    },

    configure_shirt:function(text1,text2,font_size, safari){
    	//safari override here because it can't handle loading spreadshirt into an ajax call
        if(safari != undefined){
            shirt_builder.init();
            shirt_builder.set_dynamic_text( [text1,text2], font_size, '150','150' );
            shirt_builder.build_spreadshirt_product();
            shirt_builder.open_shop_frame();
        } else {
            $('#overlay_content').addClass('purchase');
            $('#overlay_content').html("<div id='buy_shirt' class='overlay_purchase'><div id='overlayDeclaration_bgNoClick'></div><div style='position:relative;padding-top:50px;z-index:100;'><div id='loader'><img src='/image/promotions/aooak/loadingAnimation.gif' /></div></div></div>");
            $('#overlay').show('fast',function(){
                shirt_builder.init();
                shirt_builder.set_dynamic_text( [text1,text2], font_size, '150','150' );
                shirt_builder.build_spreadshirt_product();
                setTimeout(function() {
                    shirt_builder.open_shop_frame();
                }, 5000);
          //  _gaq.push(['_trackEvent','Purchase','BeginPick']);
         _gaq.push(['_trackPageview','/promotions/aooak/purchase/pick']);
            });
        }


    },
    
    spreadshirt_test:function(text1,text2){
    	shirt_builder.platform = 'dev';
        shirt_builder.init();
        shirt_builder.set_dynamic_text( [text1,text2], '40', '150','150' );
        shirt_builder.build_spreadshirt_product();
        
        var image_url = shirt_builder.get_product_image_url();
        $.get(aooak.ajaxPath+'modal/buy_shirt_1/?image='+encodeURIComponent(image_url)+'/', function(data){
			$('#spreadshirt').html(data);
        });
    },
	overlay_editDeclaration:function(){
		$('.userDeclaration a').live('click', function(){
			$('#overlay_content').removeClass('purchase');
			$('#overlay_content').load(aooak.ajaxPath+'modal/overlay_edit/ #edit_declaration', function(data){
		      $('#overlay').fadeIn('fast');
		      	// _gaq.push(['_trackEvent','Declaration','Edit']);
     	         _gaq.push(['_trackPageview','/promotions/aooak/edit_declaration']);
		    });
		});
	},
	overlay_photo:function(){
	   	$('#overlay_content').removeClass('purchase');
	    $('#overlay_content').load(aooak.ajaxPath+'modal/overlay_edit/'+randVal +' #edit_photo', function(){
	      $('#overlay').fadeIn('fast');
		  // _gaq.push(['_trackEvent','Photos','BeginEdit']);
          _gaq.push(['_trackPageview','/promotions/aooak/editphoto/start']);
	    });
	},
	overlay_pickAlbum:function(){
	 	$('#edit_photo').animate({
	      height: '586px'
	    });
	    $('.edit_photo_body').load(aooak.ajaxPath+'modal/selectAlbum/');
	   //  _gaq.push(['_trackEvent','Photos','SelectAlbum']);
        _gaq.push(['_trackPageview','/promotions/aooak/editphoto/albums']);
	},
	overlay_pickPhoto:function(album_id,album_name){
		$('#edit_photo').animate({
	      height: '586px'
	    });
		$('#picSelect_window').load(aooak.ajaxPath+'modal/selectPhoto/'+album_id+'/'+escape(album_name)+'/');
		// _gaq.push(['_trackEvent','Photos','SelectPhotoFromAlbum']);
	   _gaq.push(['_trackPageview','/promotions/aooak/editphoto/albumname']);
	},
	overlay_cropPhoto:function(photo_id, album_name){
		$('#picSelect_window').load(aooak.ajaxPath+'modal/selectCrop/'+photo_id+'/'+escape(album_name)+'/');
			window.setTimeout(function() { 
				$('#edit_photo').animate({
		      		height: '496px'
		    		}); }, 500);
			
			// _gaq.push(['_trackEvent','Photos','CropPhoto']);
	      _gaq.push(['_trackPageview','/promotions/aooak/editphoto/photo']);

	},
	overlay_declaration:function(declaration_text, image_url, user_name, updated, user_id){
		var content = create_declaration_wrapper(declaration_text, image_url, user_name, updated, user_id, true);
        $('#overlayDeclaration_content').html(content);
       //FB.XFBML.parse();
        $('#overlayDeclaration').fadeIn('fast', function() {
          var declarationLine = $('#declaration .bigtext-line0');
     	  var fSize = parseFloat(declarationLine.css('font-size'));
     	  var widthAdjustmentFactor = (fSize > 80) ? 4 : 5;
     	  var newWidth = Math.floor(fSize * widthAdjustmentFactor);
     	 if(fSize > 60) { declarationLine.css('width',newWidth); }
        });
      //  _gaq.push(['_trackEvent','Declaration','ViewDetail']);
         _gaq.push(['_trackPageview','/promotions/aooak/declare_detail']);
	},
	close_overlay:function(){
		$('#overlay').fadeOut('fast');
		$('#overlayDeclaration').fadeOut('fast');
		$('#overlay_content').removeClass('commercialOverlay');
        $('#overlay_content').html('');
		var scripts = document.getElementsByTagName("script");
		var hasFacebookScript = (scripts[0].getAttribute('id') == 'facebook-jssdk') ? true : false;
		if(hasFacebookScript == true) {
			var head= document.getElementsByTagName('head')[0];
			var isGone = head.removeChild(scripts[0]);
		}
	},
    
    showProfileHome:function(text) {
    	var profile_center = $('#declareContainer');
    	profile_center.load('/promotions/aooak/modal/profile_home/', function() {
			var userName = profile_center.find('p.userName_profile').text().split(' ');
			var firstName = userName[0];
			$('#moduleContent').load('/promotions/aooak/modal/profile_home');
	
			var navIcon =$('ul#aooak_nav div.loggedIn_avatar img');
			var newSrc = $('#profile div.profile_avatar img').attr('src');
			navIcon.attr('src',newSrc);
    	});
    }
};





var spreadshirtAPI = null;
var simplomat = null;
var userBasket = null;
var currentSize = null;
var currentAppearance = null;
var currentView = null;
var synchronized = false;
var styles = new Array();
var currentStyle = null;
var currentStyleId = null;
var design = null;
var synchronized = false;
var enableZoomIn = true;
var maxFontSize = 64;
var minFontSize = 36;
var currentProduct = null;
var browser = $.browser;
var tld = "com"; 
var spreadshirtShopId = "366628"; 



function spreadshirtsetup(productID, productSize, leftOffSet, topOffSet, height, width){
    // IE-SWITCH
    // msie, mozilla, webkit, opera

    if ( browser.msie === true || browser.opera === true ) {

        // preview enabled
        $( "a#preview" ).live('click', function() {
      	    $( "#loading2" ).show();
            $( "a#preview" ).hide();
            setTimeout("updateShirt(); $( \"#loading2\" ).hide(); $( \"a#preview\" ).show();",0);
        });

        $("#name").keypress(function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13) ) {
	    	    $( "#loading2" ).show();
                $( "a#preview" ).hide();
                setTimeout("updateShirt(); $( \"#loading2\" ).hide(); $( \"a#preview\" ).show();",0);
            } else {
                return true;
            }
        });

        $( "a#preview" ).show();
        $( "#labelFontSize" ).addClass( "ie-position-correction" );
        $( "#zoom" ).addClass( "ie-position-correction" );

    } else {

        // onkeyup enabled
        $( "input#name" ).live('keyup', function(evt) {
		if(evt.keyCode && evt.keyCode == 13)
			submitDeclaration(evt);
		else
			updateShirt();
        });

    }

    $("#promptCheckout").live('click', function() {
        simplomat.checkout();
    });

    $("#checkout").live('click', function() {
        simplomat.checkout();
    });

    $("#promptContinue").live('click', function() {
        $("#prompt").hide();
        $("#buynow").show();
        $("#checkout").show();
        $("#loading").hide();
    });

	var declaration_query = getParameterByName('declaration');
    $( "#name" ).val((declaration_query) ? declaration_query : "(30 character limit)").focus();


    //document.getElementById("designer").removeChild(document.getElementById("designer").firstChild);
    //$('#designer').html('');

    spreadshirtAPI = new SpreadshirtAPI("live", spreadshirtShopId, true);
    simplomat = new Simplomat();
    simplomat.initCallback = function() {
        $("#sizes").html("");
	$('#sizes').append('<option id="blank_size_option" value=""></option>');
        for (var i = 0; i < this.product.sizes.length; i++) {
            var size = this.product.sizes[i];
            var availableSizes = this.product.getAvailableSizes();
            var available = false;
            for (var j = 0; j < availableSizes.length; j++) {
                if (availableSizes[j] == size.id) {
                    available = true;
                    break;
                }
            }
            var onclick = "";
            var state = "";
            if (!available) {
               state = " disabled";
            }

            $("#sizes").append("<option id=\"size_" + size.id + "\" value=\"" + size.id + "\" class=\"sizeSelector " + state + "\">" + size.name + "</option>");
        }
	$('#sizes').change( function(event) {
		simplomat.product.changeSize($(event.target).find('option:selected').val());
		$('#blank_size_option').remove()
	});
        renderViews();
    };

    simplomat.priceChangedCallback = function() {
        $("#price").html(this.product.getFormatedPrice());
    };
    simplomat.sizeChangedCallback = function() {
        if (currentSize != null)
            $('#size_' + currentSize).removeClass('selected');
        currentSize = simplomat.product.sizeId;
        $('#size_' + currentSize).addClass('selected');
    };
    simplomat.viewChangedCallback = function() {
        if (currentView != null)
            $('#view_' + currentView).removeClass('selected');
        currentView = simplomat.product.viewId;
        $('#view_' + currentView).addClass('selected');
    };
    simplomat.productTypeChangedCallback = function() {
        if (currentProduct != null)
            $('#product_' + currentProduct).removeClass('selected');
        currentProduct = simplomat.product.productTypeId;
        $('#product_' + currentProduct).addClass('selected');
    }

    simplomat.basketCreatedCallback = function(basket) {
        userBasket = basket;
    }

    simplomat.productAddedToBasketCallback = function(){
        if(s !== undefined){
            s.events = "scAdd"
            if(! basketExists){
                s.events = "scOpen,"+s.events
                basketExists = true
            }
        }
    }

    simplomat.errorCallback = function(errorCode, errorMessage) {
        if(errorCode == "no_size")
            alert("Please choose a size.");
    };
    // simplomat.init( string container, int product size, , , , int productID, int color, , string printType, int position x, int position y, int width, int hight);
    simplomat.init("designer", productSize, spreadshirtAPI, false, false, null, productID, "5", "1", "flock", leftOffSet, topOffSet, width, height);
    simplomat.setBasket(userBasket);


    // positioning of your logo (tested with  star design ID: 11619331)
    // The DP logo is 11667763.
    simplomat.product.getView("1").addDesign(null, 11667763, true, null, function() {
        this.zoom(0.050);
        this.moveToRelativePosition(65, 61);
        design = this;
    });




    if (currentProduct != null)
        $('#product_' + currentProduct).removeClass('selected');
    currentProduct = simplomat.product.productTypeId;
    $('#product_' + currentProduct).addClass('selected');

    initStyles();
    updateShirt();

    setTimeout(function () {
        for (i in simplomat) {
            simplomat.R.safari();
        }
    });

}
function initStyles(){
    var standard = new Object();
    standard.name = "cooper";
    standard.fontFamilyId = 24;
    standard.fontId = 45;
    standard.iFontSize = 55;
    standard.nameFontSize = 36;
    styles.push(standard);
    selectStyle('0');
}

function selectStyle(i) {
    currentStyle = styles[i];
    currentStyleId = i;
}

function renderViews() {
    $("#views").html("");
    for (var i = 0; i < simplomat.product.views.length; i++) {
        var view = simplomat.product.views[i];
        $("#views").append("<div class=\"viewRollover\"><img id=\"view_" + view.id + "\" class=\"viewSelector\" onclick=\"javascript:simplomat.product.changeView('" +  view.id + "')\" src=\"" + simplomat.product.createViewImageUrl(view.id, simplomat.product.appearanceId, 50) + "\" width=\"50\" height=\"50\" + style=\"margin-right:5px\" /></div>");
    }
}

function updateShirt() {
    var name = $("#name").val();
    if($.cookie(aooak.cookieName)!=null){
        name = base64.decode($.cookie(aooak.cookieName));
    }
    var text = null;

    //simplomat.product.removeAll();
    simplomat.product.removeAllText();

    // this.addTextAndLayout = function(textString, maxTextLines, percentageWidth, fontFamilyId, fontId, fontSize, color, force, finalizeCallback)
    // this.addText = function(textString, fontFamilyId, fontId, fontSize, color, force, finalizeCallback)
    if (name != "" && name != "(30 character limit)"){
        simplomat.product.getView("1").addTextAndLayout(name, 5, 67, currentStyle.fontFamilyId,
            currentStyle.fontId, currentStyle.nameFontSize, "#FFFFFF", true, function() {
            text = this;
            this.moveToRelativePosition(550, 533);
        });
    }
    if (text != null) {
        text.addTextLine("I\'m a", currentStyle.fontFamilyId,
            currentStyle.fontId, currentStyle.iFontSize, "#FFFFFF", true, function() {
            text = this;
            var textLine = this.textLines[this.textLines.length-1];
            textLine.moveToRelativePosition(0, 0);
        });
    } else {
        simplomat.product.getView("1").addText("I\'m a", currentStyle.fontFamilyId,
            currentStyle.fontId, currentStyle.iFontSize, "#FFFFFF", true, function() {
            text = this;
            var textLine = this.textLines[this.textLines.length-1];
            textLine.moveToRelativePosition(425, 526);
        });
    }

}

function submitDeclaration(evt){
	evt.preventDefault();
	var decText = $('#name').val();

	if(decText == ''){
		$('.profanity-errors-container').html('<p>error: please make your declaration</p>');
		$('.profanity-errors-container').show();
		$('#name').addClass('error');
	}else{
		if(decText != '' && decText != "(30 character limit)") {
			aooak.check_profanity(decText, true, function(){
				$.cookie(aooak.cookieName,base64.encode(decText), {expires:7, path: '/'});
				if($.cookie('drpepper_user') == null) {
					$.cookie('drpepper_aooak_declare',decText, {expires:7, path: '/'});

					if($.support.leadingWhitespace == false) {
						// then we're in IE and have to scroll up first
						$('body').scrollTop(0);
					}

					aooak.dec_text = decText;
					$('#aooak_nav a.captureIframe').click();
					// _gaq.push(['_trackEvent','Declaration','Create']); 
					   _gaq.push(['_trackPageview','/promotions/aooak/declare']);
				} else {
					aooak.showProfileHome(decText);
				}
			});
		}	
	}
	
}

function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

//function centerCommercial(){
//	var commercialOffset = $('.commercialContainer').offset();
//	var commercialWidht = $('.commercialContainer').width();
//	var winWidth = $(window).width(); / 2
//	var leftMargin = winWidth - leftMargin;
	
//	alert(winWidth);
//}
function getParameterByName(name){
// Function from http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null)
		return "";
	else
		return decodeURIComponent(results[1].replace(/\+/g, " "));
}

