/**
 * Handles all the challenge related javascript for the embedded game page, including pregame challenge feed and challenge tab.
 * Please try to keep 100% self contained if possible.
 * 
 */
(function($) {
	BlockingSuccessError = function(successCallback, errorCallback, unblocks){
		this.unblocksLeft = 1;
		if(unblocks){
			this.unblockLeft = unblocks;
		};
		this.continuation = null;
		myThis = this;//silly jquery hijacking this
		this.unblock = function(){
			if(myThis.unblocksLeft==0 && myThis.continuation){
				myThis.continuation();
			}
			myThis.unblocksLeft--;
		}
		this.success = function(){
			successArgs = arguments;
			myThis.continuation = function(){
				successCallback.apply({},successArgs);
			};
			myThis.unblock();
		}
		this.error = function(){
			errorArgs = arguments;
			myThis.continuation = function(){
				errorCallback.apply({},errorArgs);
			};
			myThis.unblock();
		}
	}
	var acceptingClicks = true;
	var methods = {
		getGlobalVar : function(varName) {
			if ((typeof(GLOBAL_VARS) === 'object') && GLOBAL_VARS[varName]) {
				return GLOBAL_VARS[varName];
			}
			return null;
		},
		showProgressState: function(challengeId, replacing){
			$('.challenge-item.'+challengeId).addClass("partial");
			$('.btn-grp.'+challengeId+' .progress').show("fade", {}, 500);
			if(replacing){
				$('.btn-grp.'+replacing+' .activate.first').show("fade",{},500);
				$('.btn-grp.'+replacing+' .activate.again').css("display", "");
				$('.btn-grp.'+replacing+' .progress').hide();
				$('.challenge-item.partial.'+replacing).removeClass("partial");
				$('#challengeTemplate').setupChallengeFeed();
                $(document).trigger('challengeActivated');
			}
		},
		addChallengeClickHandlers: function(selectorPrefix){
			$(selectorPrefix+' .challenge-cta').each(function(i,el){
				var challengeId=$(el).attr('challengeId');
				var challengeType=$(el).attr('type');
				var challengeBook = $(this).attr('bookId');
				//add activate handler
				$(el).find('.btn.activateChallenge').click(function(event){
					event.stopPropagation();//don't actually go to link
					if(!acceptingClicks){return false;}acceptingClicks = false;
					//send omniture tag
					var pref = methods.getGlobalVar("OMNT_PREF");
					var code = methods.getGlobalVar("GAME_CODE");
					var pageSection = pref +'_chall_' + challengeType + '_' + code;
					OmnitureActivateEGP(challengeId, challengeType, pageSection);
					//setup poppup in case the activation fails
					bse = new BlockingSuccessError(function(data, textStatus, jqXHR){
						//success
						if(!data){//challenge was activated
							methods.showProgressState(challengeId);
							acceptingClicks = true;
						} else {//challenge wasn't activated
							$("#gameLandingTabs").tabs('select', 'challenge');
							$('#challenge').append('<div id="challengeConflict" class="egpChallengeTabPopup" style="display:none;"></div>');
							//create popup using the json data returned by ajax call
							$('#activateErrorTemplate').processFeed({
								json:data,
								replaces:'#challengeConflict',
								postLoad:function(){
									$('#challengeConflict .selectReplace').click(function(event){
										event.stopPropagation();
										$('#challengeConflict .challenge-item').removeClass('selected');
										$(this).addClass('selected');
										$('#challengeConflict .challengeConflictNotSelected').hide();
										$('#challengeConflict .challengeConflictSelected').show();
										$('#challengeConflict .selectedChallengeName').html($(this).attr('name'));
										$('#challengeConflict .selectedChallengeGame').html($(this).attr('game'));
										$('#challengeConflict .btn.disabled.replace').attr('href', $(this).attr('href'));
										$('#challengeConflict .btn.disabled.replace').attr('replace',$(this).attr('replace'));
										$('#challengeConflict .btn.disabled.replace').removeClass('disabled');
										return false;
									});
									$('#challengeConflict .btn.replace').click(function(event){
										event.stopPropagation();
										if($(this).hasClass('disabled')){
											return false;
										}
										replacing = $(this).attr('replace');
										$.ajax({
											url:$(this).attr('href'),
											success: function(data, textStatus, jqXHR){//success
												methods.showProgressState(challengeId,replacing);
												$('#challengeConflictLink').popup({cmd:'close',event:event});
											},
											error: function(jqXHR, textStatus, errorThrown){//error
												$('.btn-grp.'+challengeId+' .error').show("fade", {}, 500);
												$('#challengeConflictLink').popup({cmd:'close'});
											}
										});
										return false;
									});
								}
							});
							$('#challenge').append('<a id="challengeConflictLink" style="display:none;" href="#challengeConflict"></a>');
							$('#challengeConflictLink').popup({
								close:function(event){
									if(!event || $(event.target).hasClass('cancel')){
										//setup click handlers in the popup
										$('.btn-grp.'+challengeId+' .activate').show("fade", {}, 500);
									}
									//erase the popup so it won't show again on back button.
									$('#challengeConflict').remove();
									$('#challengeConflictLink').remove();
								}
							});
							$('#challengeConflictLink').click();
							acceptingClicks = true;
						}
					}, function(jqXHR, textStatus, errorThrown){
						//error
						$('.btn-grp.'+challengeId+' .error').show();
						acceptingClicks = true;
					});
					//start the button animation
					$('.btn-grp.'+challengeId+' .activate').hide();
					$(el).children('.activate').hide('fade', { pieces: 8 }, 500, bse.unblock);
					//try to activate challenge
					$.ajax({
						url:$(this).attr('href'),
						success: bse.success,
						error: bse.error
					});
					return false;
				});
				//add purchase handler
				var purchaseClickHandlerExplode = function(event){
					return purchaseClickHandler(event, $(this).attr('href'),'fade', { pieces: 8 });
				}
				var purchaseClickHandlerFade = function(event){
					return purchaseClickHandler(event, $(this).attr('href'),'fade', {});
				}
				var purchaseClickHandler = function(event, link, hideType, hideOp){
					event.stopPropagation();//don't actually go to link
					if(!acceptingClicks){return false;}acceptingClicks = false;
					var bse = new BlockingSuccessError(function(data, textStatus, jqXHR){
						//success
						if(challengeType=='pba'){
							$('.btn-grp.'+challengeBook+' .purchase').hide();
							$('.btn-grp.'+challengeBook+' .checkout').show("fade", {}, 500);
						} else {
							$(el).find('.checkout').show("fade", {}, 500);
							$(el).attr('clicked','yes');
						}
						//update the checkout button text
						var count=$.trim(data);
				          if((count==1)||(count==0))
				          $('.cartItemCount').html(count+" item");
				            else
				          $('.cartItemCount').html(count+" items");

						acceptingClicks = true;
					}, function(){
						$(el).find('.purchaseError').show();
						acceptingClicks = true;
					});
					$.ajax({
						url:link,
						success: bse.success,
						error: bse.error
					});
					$(el).children('.purchase').hide(hideType, hideOp, 500, bse.unblock);
					return false;
				}
				$(el).parent().next().find('a.purchase').click(purchaseClickHandlerFade);
				$(el).find('a.purchase').click(purchaseClickHandlerExplode);
			});
		},
		activated: function(c){return c.progress&&!c.progress.completed},
		completed: function(c){
				return c.progress&&c.progress.completed || c.winCount>0 || c.badge&&c.badge.winCount>0
		},
		percentDone: function(c) { return !c.progress?-1.0:Math.min(c.progress.count,c.total)/(c.total+0.0)},
		badgeTypeToNum: function(c){
			if(c.type=='mnm' && c.badge && c.badge.flash)return 5;
			if(c.type=='pba')return 4;
			if(c.type=='mnm')return 3;
			if(c.type=='pers')return 2;
			if(c.type=='weekly')return 1;
			if(c.type=='ds')return 0;
		},
        completedDSChallengeSort: function(c1,c2){
            if(c1.type=='ds' && methods.completed(c1)){
                return -1;
            }
            if(c2.type=='ds' && methods.completed(c2)){
                return 1;
            }
            return 0;
        },
		clubActiveChallengeSort: function(c1,c2){
			v1=methods.badgeTypeToNum(c1);
			v2=methods.badgeTypeToNum(c2);
			if(v1<v2){
				return 1;
			} else if(v1>v2){
				return -1;
			}
			return 0;
		},
		clubInactiveChallengeSort: function(c1,c2){
			//sort based on completion next
			if(methods.completed(c1) && !methods.completed(c2)){
				return 1;
			} else if (methods.completed(c2) && !methods.completed(c1)){
				return -1;
			}
			//put free challenge up first
			v1=methods.badgeTypeToNum(c1);
			v2=methods.badgeTypeToNum(c2);
			if(v1<v2){
				return -1;
			} else if(v1>v2){
				return 1;
			}
			return 0;
		},
		clubChallengeSort: function(c1,c2){
			//sort based on active status
			if(methods.activated(c1) && !methods.activated(c2)){
				return -1;
			} else if (methods.activated(c2) && !methods.activated(c1)){
				return 1;
			}
			if(methods.activated(c1)){
				return methods.clubActiveChallengeSort(c1,c2);
			} else {
				return methods.clubInactiveChallengeSort(c1,c2);
			}
		},
		igpClubChallengeSort: function(c1,c2){
			var v = methods.completedDSChallengeSort(c1,c2);
			if (v == 0) {
				return methods.clubChallengeSort(c1,c2);
			} else {
				return v;
			}
		},
		freeChallengeSort: function(c1,c2){
			//sort based on completion status
			if(methods.completed(c1) && !methods.completed(c2)){
				return 1;
			} else if (methods.completed(c2) && !methods.completed(c1)){
				return -1;
			}
			//put free challenge up first
			if(c1.club && !c1.club){
				return 1;
			} else if (c2.club && !c1.club){
				return -1;
			}
			//sort based on completion status
			if(methods.percentDone(c1)>methods.percentDone(c2)){
				return -1;
			} else if (methods.percentDone(c2)>methods.percentDone(c1)){
				return 1;
			}
			return 0;
		},
		igpFreeChallengeSort: function(c1,c2){
			var v = methods.completedDSChallengeSort(c1,c2);
			if (v == 0) {
				return methods.freeChallengeSort(c1,c2);
			} else {
				return v;
			}
		},
		tabshow: function(){
			var curTab = $('#gameLandingTabs .ui-tabs-nav .tab.ui-state-active');
			var selectedTab = curTab.attr('tabtitle');
			if(selectedTab=='challenge'){
				$('#tipsWeeklyLink ,#tipsMnmLink , #tipsPbaLink').popup();
				$(document).bind('challengeActivated',function(){
					$('#challengeTabTemplate').processFeed({
						'preprocessFeed':function(feed){
							var totalCompleted = 0
							active = [];
							$.each(feed,function(type,challenges){
								var completed = 0
								$.each(challenges,function(i,challenge){
									if((type=='ds' || type=='weekly') || methods.activated(challenge)) {
										active.push(challenge);
									}
									if(type!='ds' && methods.completed(challenge)){
										completed = completed + 1;
									}
								});
								challenges.completed = completed;
								totalCompleted = totalCompleted + completed;
							});
							feed.totalCompleted = totalCompleted;
							feed.active = active;
						},
						'postLoad':function(){
							methods.addChallengeClickHandlers('#egp-challenges');
							$(".challengeSection:nth-child(odd)").addClass("odd");
							// Tooltips
							$('div.challenge-item').tooltip({
								position:'center right',
								predelay:500,
								onShow: function(){
									this.getTip().prev().addClass('hover');
								}, 
								onHide: function(){
									this.getTip().prev().removeClass('hover');
								}
							});
							// Info panels
							$('a.info-close').click(function(e){
								// Prevent the default behavior of the link element
								e.preventDefault();
								// hide the parent info panel
								$(this).parents('div.challenges-info').slideUp('slow');
							});
							//chat icon activation
							$('input.setChatIcon').click(function(e){
								//the box is set to checked before this function is called.
								clickedEl = $(this);
								e.preventDefault();
								setIconUrl = '/account/profile/popup/favbadge.do?setFav='+clickedEl.val();
								if(clickedEl.prop("checked")){
									$('input.setChatIcon').prop('checked',false);
									$.ajax({
										url:setIconUrl,
										success:function(){
											$('input.setChatIcon.'+clickedEl.val()).prop('checked',true);
										},
										error:function(){
										}
									});
								} else {
									//you can't uncheck. bwa ha ha
									clickedEl.prop("checked",true);
								}
								return false;
							});
							//threeDot truncation for current challenges
							$('#currentChallenges .badgeCopy .description').ThreeDots({
								max_rows:2,
								ellipsis_string:'... <a class="showThreeDotsText" href="#">more</a>',
								alt_text_e:true,
								allow_dangle:false
							});

							$('#currentChallenges .badgeCopy .description .showThreeDotsText').click(function(event){
								event.stopPropagation();
								return false;
							});
							//threeDot truncation for badges
							$('#allChallenges div.description').ThreeDots({
								max_rows:2,
								ellipsis_string:'<a class="showThreeDotsText" href="#">...</a>',
								alt_text_e:true,
								allow_dangle:false
							});

							$('#allChallenges div.description .showThreeDotsText').click(function(event){
								event.stopPropagation();
								return false;
							});
						}
					});
				});
				$(document).trigger('challengeActivated');
			}
		},
        findIGPChallengeFunctionsFrame: function() {
            // Look in the above parent until we find the frame where the IGP Challenge info is located
            // This enables us to interact with the Game applet to get up-to-date information on challenge
            // progression.
            var p = window;
            var attempt = 0;
            while ( attempt < 5 ) {
                try {
                    if ( typeof p.getChallengeInfo == 'function' )
                        return p;
                }
                catch( err ) {
                    // ignore -- sometime an intermediary frame may be unreacheable; keep going
                }
                finally {
                    p = p.parent;  // move to the next frame
                    attempt++;
                }
            }
        }
	}

	$.fn.registerIGPChallengeCallback = function( igpChallengeInfoCallback ) {
        var containerFrame = methods.findIGPChallengeFunctionsFrame();
        if ( containerFrame ) {
            challengeInfo = containerFrame.getChallengeInfo();
            if ( JSON.stringify( challengeInfo ) != '{}' ) {
                igpChallengeInfoCallback( challengeInfo );
            }
            else {
                containerFrame.registerIGPChallengeCallback( igpChallengeInfoCallback );
            }
        }
    }

	$.fn.setupChallengeFeed = function( options ) {
		var settings = {};
		if ( options ) {
			$.extend( settings, options );
		}
		this.each(function() {
			template = $(this);

            // IGP Challenge display flow:
            //  1) Show Challenge completion or Challenge update (if any)
            //  2) Show Challenge 'up-sell' using configured feed (default)
            //p19-poppit2-puggles
            // mon3-gmasse/feed/challenge/list.do?challengeIds=p19-poppit2-puggles&poolPrice=true&addEarnedBadgeInfo=true
            // {"challenges":[{"total":800,"bookTitle":"Playful Pets","game":"Poppit!&trade;","releasedTS":1223388000000,"type":"pba","itemPrice":{"isCanGift":true,"price":101,"tag":"","DOID":"pogo:pogo:album:PREMIUM-19"},"id":"p19-poppit2-puggles","released":"Oct 7, 2008","token":1000,"description":"Win 800 tokens in 1 day!(Including Jackpot Spins)","club":true,"book":"book-premium-19","badge":{"id":"premium-19-puggles","flash":"/images/badges/lg/1693.swf","icon":"/images/badges/sm/1693.jpg","name":"Puggles Badge","winDateFormatted":"Jan 19, 2012","imageDisabled":"/images/badges/lg-d/1693.jpg","image":"/images/badges/lg/1693.jpg","flashDisabled":"/images/badges/lg-d/1693.swf","winCount":1,"shortName":"Puggles"}}]}
            if (template.attr('igp')=="true") {
                // make sure we got valid information and that the 'challenges' JSON object is an non-empty array containing at least one 'challengeId'
                if ( typeof settings.igpChallenge != 'undefined' && typeof settings.igpChallenge != 'string'
                  && typeof settings.igpChallenge.length == 'number' && settings.igpChallenge.length > 0 && typeof settings.igpChallenge[0].challengeId != 'undefined' ) {
                    // grab the completed or updated progress challenge identifier
                    var challengeId = settings.igpChallenge[0].challengeId;
                    // substitute the template's 'data' attribute to point to the single challenge feed using the id of the challenge completed (or with progress)
                    template.attr('data', '/feed/challenge/list.do?challengeIds=' + challengeId + '&poolPrice=true&addEarnedBadgeInfo=true' );
                }
            }

			template.processFeed({
				'preprocessFeed':function(feed){
					if(!feed.challenges){
						return;
					}

                    if (template.attr('igp')=="true") {
                        // if igpChallenge information was provided and it was about a challenge progresing, make sure we display the most up-to-date information
                        if ( typeof settings.igpChallenge != 'undefined' && typeof settings.igpChallenge != 'string' && typeof settings.igpChallenge.length == 'number'
                          && settings.igpChallenge.length > 0 && typeof settings.igpChallenge[0].challengeId != 'undefined'
                          && typeof settings.igpChallenge[0].progress != 'undefined' ) {
                            var newProgress = { count : settings.igpChallenge[0].progress, completed : false };
                            feed.challenges[0]["progress"] = newProgress;
                        }
                        // if igpChallenge information was provided and it was about a challenge completion, make sure we display the most up-to-date information
                        else if ( typeof settings.igpChallenge != 'undefined' && typeof settings.igpChallenge != 'string' && typeof settings.igpChallenge.length
                               && settings.igpChallenge.length > 0 && typeof settings.igpChallenge[0].completed != 'undefined' ) {
                            // Overload the 'progress' attribute
                            var newCompletion = {completed : true};
                            feed.challenges[0]["progress"] = newCompletion;
                        }
                        // apply IGP specific sorting
                        else {
                            if(template.attr('club')=="true"){
                                feed.challenges = feed.challenges.sort(methods.igpClubChallengeSort);
                            } else {
                                feed.challenges = feed.challenges.sort(methods.igpFreeChallengeSort);
                            }
                        }
                    }
                    else {
                        // EGP specific sorting
                        if(template.attr('club')=="true"){
                            feed.challenges = feed.challenges.sort(methods.clubChallengeSort);
                            if(feed.challenges.length>0 && feed.challenges[0].progress && feed.challenges[0].progress.completed){
                                feed.challenges.length=0;
                            }
                        } else {
                            feed.challenges = feed.challenges.sort(methods.freeChallengeSort);
                        }
                    }

					if(feed.challenges.length>1){
						feed.challenges.length=1;
					}
					if (typeof OmnitureLightEvent === 'function') {
						// fire light server call for challenge impression
						if (feed.challenges != null && feed.challenges.length>0){
							var code = methods.getGlobalVar("GAME_CODE");
							var pref = methods.getGlobalVar("OMNT_PREF");
							OmnitureLightEvent(pref +'_chall_' + feed.challenges[0].type + '_' + code, false);
						}
					}

                    // remove waiting animation
                    if (template.attr('igp')=="true") {
                        $('#challengeWaitingArea').hide();
                    }
				},
				'postLoad':function(){
					$('#challengeArea .badgeCopy .description').ThreeDots({
						max_rows:2,
						ellipsis_string:'... <a class="showThreeDotsText" href="#">more</a>',
						alt_text_e:true,
						whole_word:true
					});
					$('#challengeArea .showThreeDotsText').click(function(event){
						event.stopPropagation();
						return false;
					});
					methods.addChallengeClickHandlers('#challengeArea');
//					$('.swfLoader.pba').each(function(i,el){
//					   var so = new SWFObject($(el).attr('data'), "mymovie", "400", "200", "8", "#336699");
//					   so.write($(el).attr('id'));
//					});

					if (template.attr('igp')=="true" && template.attr('auth')=="false"){
						$("#igp-challenge-signup").popup();
						$("#igp-challenge-signin").popup();
					}

                    if ( template.attr('igp') == "true" ) {
                        var containerFrame = methods.findIGPChallengeFunctionsFrame();
                        if ( containerFrame ) {
                            containerFrame.clearChallengeInfo();
                        }
                    }
				}
			});
		});
	}
	
	$(document).ready(function() {
		var gameLandingTabs = $("#gameLandingTabs");
		if (gameLandingTabs && gameLandingTabs.length) {
			var numTabs = gameLandingTabs.tabs('length');
			gameLandingTabs.bind('tabsshow', methods.tabshow);
			if(numTabs>0){
				//check if tab is loaded via #challenge
				methods.tabshow();
			}
		}
		
	});
})(jQuery);

