/**
 * @author Srini/Pritam/Ashvin
 * @Jquery Plugin for wmg features
 */

jQuery.wmgfeature = function(opts){
    if (!opts) {
        return;
    }
    var opts = jQuery.extend({}, jQuery.wmgfeature.defaults, opts);
    if (opts.tweetmeme.switchOn) {
        jQuery.wmgfeature.tweetmeme(opts.tweetmeme.pageName, opts.tweetmeme.siteURL, opts.tweetmeme.insertBefore);
    }
    if (opts.iggli.switchOn) {
        jQuery.wmgfeature.iggli.addIggli(opts.iggli.selector, opts.iggli.partnerId);
    }
    if (opts.facebookShare.switchOn) {
        jQuery.wmgfeature.facebooklike(opts.facebooklike.insertBefore);
    }
    if (opts.welcomescreen.switchOn) {
        jQuery.wmgfeature.welcomescreen(opts.welcomescreen.selector, opts.welcomescreen.message);
    }
    if (opts.roaster.switchOn) {
        jQuery.wmgfeature.roaster(opts.roaster.startVal, opts.roaster.repeatVal, opts.roaster.message);
    }
};


jQuery.wmgfeature.defaults = {
    tweetmeme: {
        switchOn: 'off',
        blockSelector: '',
		urlSelector: '',
		urlQualifier: '',
		insertionSelector: ''
    },
    facebooklike: {
        switchOn: 'off',
        blockSelector: '',
		urlSelector: '',
		urlQualifier: '',
		insertionSelector: '',
		siteURL:''
    },
    welcomescreen: {
        switchOn: 'off',
        selector: '',
        message: ''
    },
    roaster: {
        switchOn: 'off',
        startVal: '',
        repeatVal: '',
        message: ''
    },
    iggli: {
        switchOn: 'off',
        selector: '',
        partnerId: ''
    },
    feedback: {
        switchOn: 'off',
        linkToURL: ''
    }

};

/**
 * Feedback Feature
 */
jQuery.wmgfeature.feedback = function(linkToURL){
    if ($('body.m32').length == 0) {
        $("body").append("<div class='widget'><a style='background-color: rgb(34, 34, 34);' class='fdbk_tab_left' id='fdbk_tab' href='" + linkToURL + "'>FEEDBACK</a></div>");
		
		/* That little Wiggle Effect */
		$("#fdbk_tab").hover(function(){
				$(this).animate({'margin-right' : 0},250);
			},function(){
				$(this).animate({'margin-right' : -7},250);
		});
    }
}

/**
 * Facebook Like Feature
 * @param blockSelector: each list item selector for different pages
 * @param urlSelector: relative path of the post
 * @param urlQualifier: to get the href attribue of the anchor tag 
 * @param insertionSelector: to insert the button
 * @param siteURL: url of the site
 * @param detailPageUrl: url for the detail pages
 */

jQuery.wmgfeature.facebookLike = function(blockSelector,urlSelector,urlQualifier,detailPageUrl,insertionSelector,siteURL){
    var url;
    var fbLike;
    var fbLikeUrl;    
    if (detailPageUrl == null){    	
    	$(blockSelector).each(function(){
			if ($(this).find('.fb_like').length == 0) {
				url = $(this).find(urlSelector).attr(urlQualifier);
				fbLikeUrl = siteURL + url;
				fbLike = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + fbLikeUrl + '&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:90px; height:21px"></iframe>';
				$(this).find(insertionSelector).after('<div class="fb_like" style="float:left;">' + fbLike + '</div>');
			}
		});
    } else {
		if ($(blockSelector).find('.fb_like').length == 0) {
			fbLike = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + detailPageUrl + '&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:90px; height:21px"></iframe>';
			$(blockSelector).find(insertionSelector).after('<div class="fb_like" style="float:left;">' + fbLike + '</div>');
		}
	}
           
};

/**
 * Facebook Share Feature
 * @param blockSelector: each list item selector for different pages
 * @param urlSelector: relative path of the post
 * @param urlQualifier: to get the href attribue of the anchor tag 
 * @param insertionSelector: to insert the button
 * @param siteURL: url of the site
 * @param detailPageUrl: url for the detail pages
 */
jQuery.wmgfeature.facebookShare = function(blockSelector,urlSelector,urlQualifier,detailPageUrl,insertionSelector,siteURL){
    var url;
    var fbShare;
    var fbShareUrl;    
    if (detailPageUrl == null){    	
    	$(blockSelector).each(function(){
			if ($(this).find('.fb_share').length == 0) {
				url = $(this).find(urlSelector).attr(urlQualifier);
				fbShareUrl = siteURL + url;
				fbShare = '<a name="fb_share" type="button" style="float: left; cursor: pointer; position: absolute;" share_url="' + fbShareUrl + '">Share</a>';
				$(this).find(insertionSelector).after('<div class="fb_share" style="float:left;">' + fbShare + '</div>');
			}
		});
    } else {
		if ($(blockSelector).find('.fb_share').length == 0) {
			fbShare = '<a name="fb_share" type="button" style="float: left; cursor: pointer; position: absolute;" share_url="' + detailPageUrl + '">Share</a>';
			$(blockSelector).find(insertionSelector).after('<div class="fb_share" style="float:left;">' + fbShare + '</div>');
		}
	}
           
};

/** 
 * Tweetmeme Feature
 * @param blockSelector: each list item selector for different pages
 * @param urlSelector: relative path of the post
 * @param urlQualifier: to get the href attribue of the anchor tag 
 * @param insertionSelector: to insert the button
 * @param siteURL: url of the site
 * @param detailPageUrl: url for the detail pages
 */
jQuery.wmgfeature.tweetmeme = function(blockSelector,urlSelector,urlQualifier,detailPageUrl,insertionSelector,siteURL){
    var url;
    var retweet_me;
	var tweetmemeURL;
	
	if (detailPageUrl == null){
		$(blockSelector).each(function(){
			if ($(this).find('.retweet_me').length == 0) {
				url = $(this).find(urlSelector).attr(urlQualifier);
				tweetmemeURL = siteURL + url;
				retweet_me = '<iframe scrolling="no" allowTransparency="true" height="20" frameborder="0" width="90" src="http://api.tweetmeme.com/button.js?url=' + tweetmemeURL + '&style=compact&service=bit.ly&service_api=R_6287c92ecaf9efc6f39e4f33bdbf80b1"></iframe>';
				$(this).find(insertionSelector).after('<div class="retweet_me" style="float:left;">' + retweet_me + '</div>');
			}
		});
	} else {
		if ($(blockSelector).find('.retweet_me').length == 0) {
			retweet_me = '<iframe scrolling="no" allowTransparency="true" height="20" frameborder="0" width="90" src="http://api.tweetmeme.com/button.js?url=' + detailPageUrl + '&style=compact&service=bit.ly&service_api=R_6287c92ecaf9efc6f39e4f33bdbf80b1"></iframe>';
			$(blockSelector).find(insertionSelector).after('<div class="retweet_me" style="float:left;">' + retweet_me + '</div>');
		}
	}       
};

/** 
 * Toaster Feature
 */

jQuery.wmgfeature.roaster = function(startVal, repeatVal, message){
    var regFooterVar = document.createElement('div');
    $(regFooterVar).attr("id", "regFooter");
    $(regFooterVar).css({
        'display': 'none'
    });
	
	if(userEmail != "" &&  userEmail != null){
     	$(regFooterVar).append('<div id="regFooterWrapper"><div id="regFooterLeft"><label id="regFooterLabel">' + message + '</label><a id="regFooterSign" href="/join" ></a></div><div id="regFooterRight"><a id="regFooterClose"></a></div><div class="clear"></div></div>');
     } else {
     	$(regFooterVar).append('<div id="regFooterWrapper"><div id="regFooterLeft"><label id="regFooterLabel">' + message + '</label><a id="regFooterSign" href="/sign-up" ></a></div><div id="regFooterRight"><a id="regFooterClose"></a></div><div class="clear"></div></div>');
     }
	 
    $("#footer").append(regFooterVar);
    
    $(function(){
        $("#regFooter a#regFooterClose").bind('click', function(event){
            $("#regFooter").slideToggle();
        });
    });
    
    if ($('li.signup a').length != 0) {
        userVisitCount = $.cookie("userVisits2");
        userVCount = parseInt(userVisitCount);
        userVCountPhase2 = parseInt($.cookie("userVisits2Phase2"));
        
        if (userVisitCount == null) {
            userVCount = 1;
        }
        else {
            userVCount = userVCount + 1;
            if (null != parseInt($.cookie("userVisits2Phase2"))) {
                userVCountPhase2 = userVCountPhase2 + 1;
            }
        }
        writeToConsole(userVCount);
        
        if (userVCount == startVal) {
            $("#regFooter").slideToggle();
            $.cookie("showJoinError1", "Yes", {
                path: '/'
            });
            $.cookie("showMusicRstError1", "No", {
                path: '/'
            });
            
            userVCountPhase2 = 0;
            
        }
        else if (userVCount != startVal && null != userVCountPhase2 && userVCountPhase2 % repeatVal == 0) {
                $("#regFooter").slideToggle();
   		}
        
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        $.cookie("userVisits2", userVCount, {
            path: '/',
            expires: date
        });
        if (userVCount >= startVal) {
            $.cookie("userVisits2Phase2", userVCountPhase2, {
                path: '/',
                expires: date
            });
        }
    }
    else {
        $.cookie("userVisits2", null);
		$.cookie("userVisits2Phase2", null);
    }
    
}

/** 
 * Welcome Screen Feature
 */
jQuery.wmgfeature.welcomescreen = function(selector, message){
    if($(""+selector+":contains('"+message+"')").length > 0){
    	var url = "/welcome/?KeepThis=true&TB_iframe=true&height=400&width=600&modal=true";
    	if (parent.$("#TB_window").html() == null) {
        	tb_show(null, url, false);
    	}
    }	  
};

/**
 * Iggli Feature
 */
jQuery.wmgfeature.iggli = function(selector, partnerId){
    var invite_location;
    var invite_title;
    var invite_date;
    var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    
    var monthJson = {
        "monthNameToNumMap": {
            "some": [{
                "name": "Jan",
                "num": "01"
            }, {
                "name": "Feb",
                "num": "02"
            }, {
                "name": "Mar",
                "num": "03"
            }, {
                "name": "Apr",
                "num": "04"
            }, {
                "name": "May",
                "num": "05"
            }, {
                "name": "Jun",
                "num": "06"
            }, {
                "name": "Jul",
                "num": "07"
            }, {
                "name": "Aug",
                "num": "08"
            }, {
                "name": "Sep",
                "num": "09"
            }, {
                "name": "Oct",
                "num": "10"
            }, {
                "name": "Nov",
                "num": "11"
            }, {
                "name": "Dec",
                "num": "12"
            }, ]
        }
    };
    
    populateInviteData = function(){
        //all the possible fields in this json object
        json = {
            widget_version: "2.0",
            widget_skin: "button_square_small",
            partner_id: partnerId, //Do not change this id. This is unique
            title: iTitle,
            location: iLocation,
            date: iDate
        }
        
        //replace any current invite data using the json object
        inviteButtons[0].setOptions(json);
        
        //refresh the html to reflect new data
        inviteButtons[0].refresh();
        
        // launch the invite
        loadInviteInModal(0);
        
    }
    
    addIggli = function(selector){
        $(selector).each(function(){
            invite_locationCity = "";
            invite_locationRegion = "";
            invite_title = "";
            invite_date = "";
            inviteDateArr = "";
            inviteMonName = "";
            invite_title = $(this).find('.event_location .venue').text();
            invite_locationCity += $(this).find('.event_location .location .city').text();
            invite_locationRegion += $(this).find('.event_location .location .region').text();
            inviteDateInHtml = $(this).find('.date h4 a').text();
            inviteDateArr = inviteDateInHtml.split(" ");
            if (inviteDateArr.length <= 0) {
                return;
            }
            inviteMonName = inviteDateArr[0];
            if (inviteMonName.length > 3) {
                inviteMonName = inviteMonName.substring(0, 3);
            }
            inviteDate = inviteDateArr[1].substring(0, inviteDateArr[1].length - 1);
            inviteYear = inviteDateArr[2];
            for (icnt = 0; icnt < 12; icnt++) {
                if (monthJson.monthNameToNumMap.some[icnt].name.toLowerCase() == inviteMonName.toLowerCase()) {
                    inviteMon = monthJson.monthNameToNumMap.some[icnt].num;
                    break;
                }
            }
            invite_date = inviteMon + "/" + inviteDate + "/" + inviteYear;
            invite_location = $.trim(invite_locationCity) + $.trim(invite_locationRegion);
            onclickString = "populateInviteData('" + $.trim(invite_title) + "','" + $.trim(invite_location) + "','" + $.trim(invite_date) + "');";
            $(this).append('<div class="iggli-invite-button"><a class="iggli-button" onclick="' + onclickString + '">Invite Friends</a></div>');
            
        });
    };
    
};

/**
 * SP Migration Code
 */
jQuery.wmgfeature.sptoEOS = function(topContainerId, isUpdate, arrElementIDs, siteName, siteId) {
	
	var elementCountryValue ="";

	if ($("#replaceScriptRSUP").length > 0) {
		script = $("#replaceScriptRSUP");
		if ($(script).length > 0) {
			$("#replaceScriptRSUP").empty();
		}
	}

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.id = 'replaceScriptRSUP';
	var src = 'http://sms.wmg.com/sms/register?js=true';
	if(isUpdate) {
		src += '&updateprofile=yes';
	}
	
	for (var elementId in arrElementIDs) {
		var element = document.getElementById(elementId);
		if (element != null) {
			if ((element.type == 'text' || element.type == 'select-one' || element.type == 'select') || (element.type == 'radio' && element.checked == true)) {
			
				if ((src.indexOf(arrElementIDs[elementId]) == -1) && (element.value != "")) {
					src += "&" + arrElementIDs[elementId] + "=" + jQuery.trim(element.value);
					if (arrElementIDs[elementId] == "country") {
						elementCountryValue = element.value;
					}
				}
			}
		}
	}
	
	if(EmailListIds[elementCountryValue]) {
		newsletterIdValRS = EmailListIds[elementCountryValue];					
	} else {
		newsletterIdValRS = EmailListIds['United States'];
	}
	
	var signuptypeValRS = "any";
	
	src += "&newsletterId=" + newsletterIdValRS;
	src += "&signuptype=" + signuptypeValRS;
	src += '&EosSiteAccountId='+aSiteUserId;
	src += '&EosMasterAccountId='+aUserId;
	if(src.indexOf("email") == -1){
		src += "&email=" + userEmail;
	}
	if((src.indexOf("EosUserDisplayName")== -1) && (auserName != "")){
		src += "&EosUserDisplayName=" + auserName;
	}
	if( false == isUpdate){
		src += '&siteName=' + siteName;
		src += '&SiteId=' + siteId;
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth()+1;
		var curr_year = d.getFullYear();
		src += '&EosSiteRegistrationDate=' + curr_month + '-' + curr_date + '-' + curr_year;
	}
	 
	script.src = src;
	try {
		chkRS = true;
		document.getElementById(topContainerId).appendChild(script);
	} catch (err) {
	}
	setTimeout("alertTimeoutError()", 10000); // wait for 8 seconds	
};

jQuery.wmgfeature.spFeatureJoin = function(selector, moduleContainerId, isUpdate, arrElementIDs, siteName, siteId){
	
	$(selector).removeAttr("onclick");
	$(selector).click(function(event) {
		event.preventDefault();
		jQuery.wmgfeature.sptoEOS(moduleContainerId, isUpdate, arrElementIDs, siteName, siteId);
	});
	
};

jQuery.wmgfeature.spFeatureEditProfile = function(selector, moduleContainerId, isUpdate, arrElementIDs, siteName, siteId) {
	
	$(selector).removeAttr("onclick");
	$(selector).click(function(event) {
		event.preventDefault();
		jQuery.wmgfeature.sptoEOS(moduleContainerId, isUpdate, arrElementIDs, siteName, siteId);
	});
};

jQuery.wmgfeature.spFeatureEditAccountAccData = function(selector, moduleContainerId, isUpdate, arrElementIDs, siteName, siteId) {
	
	$(selector).removeAttr("onclick");
	$(selector).click(function(event) {
		event.preventDefault();
		jQuery.wmgfeature.sptoEOS(moduleContainerId, isUpdate, arrElementIDs, siteName, siteId);
	});
};

jQuery.wmgfeature.spFeatureEditAccountAccQuestions = function(selector, moduleContainerId, isUpdate, arrElementIDs, siteName, siteId) {
	
	$(selector).removeAttr("onclick");
	$(selector).click(function(event) {
		event.preventDefault();
		isAccountQuestions = true;
		jQuery.wmgfeature.sptoEOS(moduleContainerId, isUpdate, arrElementIDs, siteName, siteId);
	});
};

jQuery.wmgfeature.spCallback = function(selector,scenarioType){
	
	if(scenarioType == "joinScreen"){
		$(selector).modulePerformAction('join');
	}else if(scenarioType == "editProfile"){
		$(selector).modulePerformAction('update-profile', {
				successFunction: eos.ui.bindUploadAvatar
		});
	}else if(scenarioType == "editAccOues"){
		$(selector).modulePerformAction('update-account-questions');
	}else if(scenarioType == "editAccNormal") {
		$(selector).modulePerformAction('update-account');
	}
};


/* 
 * Jquery Plugin to scroll to an ID. 
 * Usage - $("#id").scrollToViewPort("slow");
 * Parameters Taken - Time in Milliseconds, or "slow,"fast";
*/
jQuery.fn.scrollToViewPort = function(animTimeInterval) {
  animTimeInterval = (typeof animTimeInterval == "undefined")?"slow":animTimeInterval;
  return this.each(function(){
    $('html,body').animate({scrollTop: $(this).offset().top},animTimeInterval);
  });
};


/*
 * Jquery Plugin - opens external links in a new window.
 * Checks if the links are relative, and are of the same domain.
 * Sampe Usage - $("#someDiv a").makeLinksExternal();
*/
jQuery.fn.makeLinksExternal=function(){return this.each(function(){var a=$(this).attr("href");if(a.indexOf(location.host)==-1&&a.indexOf("/")!=0){$(this).attr("target","_blank")}})};
 

/* Supplant Function. Remedial JS. Thanks to Douglas Crockford. 
 * Substitues the variables in a string. The variables must be preceded by {}.
 * 
*/
if(!String.prototype.supplant){String.prototype.supplant=function(a){return this.replace(/{([^{}]*)}/g,function(d,c){var e=a[c];return typeof e==="string"||typeof e==="number"?e:d})}};


