/*!
 * Common mYusic script functions!
 */
 
//variable used to tell the player that the user is logged into facebook

var HAS_FRIEND_PERM_COOKIE_NAME = "HasFriendPerms";
var DSPL_REG_SCREEN_COOKIE_NAME = "RegScreenFlag";
var DSPL_FRND_LIKE_COOKIE_NAME = "FriendLikeFlag";
var apptype="";
var objJSONList = new JSONList();
var loggedIn = getLoggedinStatusCookie(); //0 - not logged in, 1 - logged in via FB, 2 - logged in via mYusic
var hasFriendPermissions = getCookie(HAS_FRIEND_PERM_COOKIE_NAME, 1);  //0=No, 1=Yes, -1=havent checked
var haveDisplayedRegsiterScreen = getCookie (DSPL_REG_SCREEN_COOKIE_NAME, 0);
var haveDisplayedFrndLikeScreen = getCookie (DSPL_FRND_LIKE_COOKIE_NAME, 1);
var userFirstName = ""


  $.ImagePreload("/DailyPosts/images/fbRegister.jpg");
  $.ImagePreload("/DailyPosts/images/mRegister.jpg");
  $.ImagePreload("/DailyPosts/images/secure_Account.jpg");



function JSONList()
    {
        this.JsonFacetList ="";
        this.JsonSongList = "";
        this.JsonSaveChannelList = "";
        this.JsonRetriveChannellList = "";
        this.JsonDeletechannelData ="";
		this.JsonMapProfileData="";
		this.JsonRegFormData="";
		this.JsonLoginFormData="";
		this.JsonFeedbackFormdata="";
		this.JsonEmailPreferencesData="";
    }


function openPlayerWindow(playerParams, autoPlay)
{
    var baseURL = "/app/player?q=";
	var queryURL = baseURL.concat(playerParams);
    var url = queryURL;
	
	if (apptype=="fb")
	{
        checkTimelinePermissions ();	    
		url = queryURL.concat("&apptype=fb");		
	}	
	//alert (url);
	if (autoPlay) {
	  
	  existingOrNot = window.open("","PLAYER", "width=1040,height=645,status=0,toolbar=0,menubar=0,scrollbars=0,resizable=0");
	  
	  if (existingOrNot == null || existingOrNot.location.href.indexOf ("blank") != -1){	    
	    playerWin = window.open(url,"PLAYER", "width=1040,height=645,status=0,toolbar=0,menubar=0,scrollbars=0,resizable=0");  
		window.focus();
	  } 
	  
	} else {
	  playerWin = window.open(url,"PLAYER", "width=1040,height=645,status=0,toolbar=0,menubar=0,scrollbars=0,resizable=0");
      playerWin.focus();
	}  
}

function setLoginRegisterationFormLocation()
{
		    var	loginandregDiv = $('#loginandregDiv_Id'); 	 			   
	        var popMargTop = (loginandregDiv.height() ) / 2;
            var popMargLeft = (loginandregDiv.width() ) / 2;

           //Apply Margin to Popup
            loginandregDiv.css({
                'margin-top' : -popMargTop,
                'margin-left' : -popMargLeft
            });		   


		   loginandregDiv.fadeIn();

}


function showmYusicLoginForm()
{
	try
	    {
           setLoginRegisterationFormLocation();    
           $("#loginForm_id").show();
		   $("#registrationForm_id").hide();	   
		   			   
		   document.getElementById("txtuseridloginFrm").focus();		   			  

		}catch(err)
            {
              alert(err.description);
            } 
}


	 function showRegistrationForm()
	 {
	     try
		    {
			  // initializeGoogleAddress();
			  // emptyRegForm();
			  // $("#txtuseridregFrm").show();
			   setLoginRegisterationFormLocation();
			   $("#loginandregDiv_Id").show();	
			   $("#loginForm_id").hide();	
			   $("#registrationForm_id").show();
			   $("#checktermsflag").attr('checked','');
			   document.getElementById("txtuseridregFrm").focus();			  		 
			   var mydate=new Date();
               var year=mydate.getYear();    
               if (year < 1000){
                  year+=1900;
				} 
               $("#selectedyear").val(year-14);
			   $("#maleradiobtn").attr('checked','checked');     			   
			   $("#trans_div_register_id").show();
			}catch(err)
            {
              alert(err.description);
            } 
	 }

	 function hideloginForm()
	 {
	    try
		    {
			  //emptyloginform();
			  

			  $('#loginandregDiv_Id').hide();
			  
	     }catch(err)
            {
              alert(err.description);
            } 
	 }
	 
	function hideRegistrationForm()
	 {
	    try
		   {
			  // emptyRegForm();
			 //  $("#registrationForm_id").hide();
			   $("#loginandregDiv_Id").hide();			
			//   $("#trans_div_register_id").hide();
		   }catch(err)
            {
              alert(err.description);
            } 
	 }	 
	 
	 // check Password strength weak or strong.
	 function checkPasswordStrength()
	 {
	    chkpasswordstrengthRegForm = $("#txtpwdregFrm").val(); 
	    if((chkpasswordstrengthRegForm.length < 6))
		{
          $("#passworderrorMsgregFrm").html("Please enter more then 6 characters");
		  return false;
		}else
		{
		  $("#passworderrorMsgregFrm").html("");
          return true;
		}  
	 }	 
	 
	 function submitloginForm()
	 {
	   try
		   {
 
			 if(validateloginForm()){			
	             var userIdLoginFrom =  $("#txtuseridloginFrm").val();
                 var passwordLoginFrom = $("#txtpwdloginFrm").val();				 
              //   alert("ID:"+userIdLoginFrom+"......password...."+passwordLoginFrom);				 
				 $.ajax({
				  type:"POST",
				  url:"/soachapi/checklogin",
				  data:{'username':userIdLoginFrom,'password':passwordLoginFrom},
				  success:function(data) {  
				  if(data.length>0) {
					 objJSONList.JsonLoginFormData = data;
					// objJsonLoginFormParse = jQuery.parseJSON(objJSONList.JsonLoginFormData);					
					 if(objJSONList.JsonLoginFormData == "Authentication failed")
					  {	
						  $("#loginserviceerrorMsg").html("Authentication failed");							
					  }else
					  {	
                       loggedIn = 2;                    
                       displayLogoutButton();  
					   setLoggedinStatusCookie (loggedIn);					  
					   hideloginForm();					 
                     					  
					  }
				    }
				},
				  error:function(xhr,err){
					  if(xhr.status != 500){
						 alert("Oops! Looks like we did something wrong. please try again.");
					  }	
					}
					});	
			 }		
        }catch(err)
            {
			 // hideloginForm();
              alert (err.description);
            } 	 
	 }
	 
	 
	 function validateloginForm()
	 {
	     try
		    {
			   var userIdLoginForm =  $("#txtuseridloginFrm").val();
			   var passwordLoginForm = $("#txtpwdloginFrm").val();
			   if(userIdLoginForm == "" || userIdLoginForm == null){
					$("#useriderrorMsgloginFrm").html("Please enter user Id");
					return false;
				}else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(userIdLoginForm))){
					$("#useriderrorMsgloginFrm").html("Please enter valid email-id");
					return false;
				}else if(passwordLoginForm == "" || passwordLoginForm == null){
					$("#passworderrorMsgloginFrm").html("Please provide password");
					return false;
				}else
				{
				 return true;
				}
		 }catch(err)
            {
              alert(err.description);
            } 
	 }
	 
	 // Check validation & call to ajax for registration.
	 function submitRegForm()
	 {
	  
	   try
		   {
			 if(validateRegisterationForm()){		
		    		
				 var passwordRegForm = $("#txtpwdregFrm").val();
	             var userIdRegForm =  $("#txtuseridregFrm").val();
				 var gender=$("input[name=rdogender]:checked").val();
				 var chkgender = (gender == 'Male') ? 'M' : 'F';				 
                 var selectedyear=$("#selectedyear").val();
				 var hometownaddress=$("#address").val();
				 var zipcode=$("#txtZipCoderegFrm").val();
				 var termsval = 1;
				// var mapAuthTypeRegForm = $("#selauthtyperegFrm").val();
                 $("#registrationForm_id").css('cursor','wait');				
				 $.ajax({
				  type:"POST",
				  url:"/soachapi/registeruser",
				  data:"emailid="+encodeURIComponent(userIdRegForm)+"&authKey="+encodeURIComponent(passwordRegForm)+"&gender="+chkgender+"&year="+selectedyear+"&location="+encodeURIComponent(hometownaddress)+"&zipcode="+encodeURIComponent(zipcode)+"&termsvalflag="+encodeURIComponent(termsval),
				  success:function(data) {  
				  if(data.length>0) {	  
					 objJSONList.JsonRegFormData = data;					
					 objJsonRegFormParse = jQuery.parseJSON(objJSONList.JsonRegFormData);				    				 
					 if(objJsonRegFormParse == "OK")
					  {					   
					     hideRegistrationForm();						 
						 loggedIn = 2;	
						 displayLogoutButton();  
					     setLoggedinStatusCookie (loggedIn);		
						 //displaylogoutdiv(1);  // 1 - For web logout                      
                        						
					  }else if(objJsonRegFormParse.code == objConfig.errorregistrationJSON)
					  {					  
					    $("#regserviceerrorMsg").html("User already exists. Please try a different User ID.");
						$("#registrationForm_id").css('cursor','default')						
					  }else
					  {					 
					    $("#regserviceerrorMsg").html("Oops! Looks like we did something wrong. please try again.");
						$("#registrationForm_id").css('cursor','default')					 
					  }
					   $("#registrationForm_id").css('cursor','default');	
				    }
				},
				   error:function(xhr,err){
					  if(xhr.status != 500){
						 alert("Oops! Looks like we did something wrong. please try again.");
						 $("#registrationForm_id").css('cursor','default');
					  }	
					}
					});		
			 }		
        }catch(err)
            {
			   hideRegistrationForm();
               alert( err.description );
            } 	 
	 }
	
	 // validate  Registration form
	 function validateRegisterationForm()
	 {

		 try
		   {			
			var passwordRegForm = $("#txtpwdregFrm").val();
			var userIdRegForm =  $("#txtuseridregFrm").val();
			var confrimPwdRegForm =  $("#txtconfirmpwdregFrm").val();
			var zipcodeRegForm = $("#txtZipCoderegFrm").val();
			var locationRegForm = $("#address").val();

			if(userIdRegForm == "" || userIdRegForm == null){
				$("#useriderrorMsgregFrm").html("Please enter user Id");

				return false;
			}else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(userIdRegForm))){
				$("#useriderrorMsgregFrm").html("Please enter valid email-id");

				return false;
			}else if(passwordRegForm == "" || passwordRegForm == null){
				$("#passworderrorMsgregFrm").html("Please provide password");

				return false;
			}else if(confrimPwdRegForm == "" || confrimPwdRegForm == null){
				$("#confirmpwderrorMsgregFrm").html("Please provide password");

				return false;
			}else if(passwordRegForm != confrimPwdRegForm){
			   $("#passworderrorMsgregFrm").html("Password does not match");

			   return false;
			}else if(!checkPasswordStrength())
			{        

			  return false;
			}else if(zipcodeRegForm == "" || zipcodeRegForm == null){
			  $("#zipCodeerrorMsgregFrm").html("Please enter zipcode or pincode");
		
			  return false;
			}else if(!isValidZipCode(zipcodeRegForm)){
			  $("#zipCodeerrorMsgregFrm").html("Please enter valid zipcode or pincode");
		
			  return false;
			}
			else if(!$('input[name=checktermsflag]').is(':checked')) 
			{
				$("#termserrorMsgregFrm").html("Please read and accept the Terms of Service");

				return false;
			}
			else{

			   return true;			   
			}
		}catch(err)
            {
              alert (err.description);
            } 
			
	 }
	 
	 function isValidZipCode(value)
	 {
	   var re = /^[0-9a-zA-Z]{0,}[\-]?[0-9a-zA-Z]{0,}$/; 
	   return (re.test(value));
     }	 
	 
//Check is the user is logged in via mYusic
$(document).ready(function() {

    $('.regFormImg').click(function(e){
	  $(e.target).parent().parent().parent().parent().css({'display' : 'none'});	
	  $('#fade').remove();
	});
	
	
	
	if (loggedIn == 2 || loggedIn ==1)
    {
	 setLoggedinStatusCookie (loggedIn);
	 setCookie (DSPL_REG_SCREEN_COOKIE_NAME, 1);
	 displayLogoutButton();
    } 
	
	var playerLink = document.getElementById("dpPlayerLink");
	if (playerLink != null){
	   strFunctionString = $(document).find('#dpPlayerLink').attr("onClick");
	   var functionTokens = strFunctionString.split("'");
	   strPlayerQuery = functionTokens[1];
	   
	   openPlayerWindow (strPlayerQuery, 1);

	}	
});	  

function doLogout()
{

 

   var chkMode; // 0 - Facebook eject , 1 - Web logout
    if (loggedIn == 2)
	{
	  chkMode = 1;   
	}else if (loggedIn == 1){
	  chkMode = 0 ; 
	}
	
	try
	    {
		$.ajax({
				type:"POST",
				url:"/logout/logout",
				data:{'logoutmode':chkMode},
				success:function(data) {
				    
					if(data.length>0) {
					     //empty all data
						 loggedIn = 0; 
						 setLoggedinStatusCookie(0);
                         restoreLoginButtons();           
						
						if(chkMode == 0)
						{
							FB.logout(function(response) {
								window.location.reload();
							});
						} else{
						    window.location.reload();
						}						 
					}					
				},
				error:function(xhr,err){
				  if(xhr.status != 500){
					  alert("Oops! Looks like we did something wrong. Please try again.");
				  }		
				}
				});  //end ajax call	
		
        }catch(err)
	      {		
		     alert (err.description);
	     }
	
	
}

function displayLogoutButton()
{
    
    $('#loginRegMessage').html('');
	
	if (loggedIn == 2){
        $('#userName').html('<a onClick="doLogout()" href="javascript:void()"> <img style="margin:auto;" src="/DailyPosts/images/mLogout.jpg" id="mYusicLogout" /></a>');
		
	}
	if (loggedIn == 1){
	    $('#userName').html('<a onClick="doLogout()" href="javascript:void()"> <img style="margin:auto;" src="/DailyPosts/images/fbLogout.jpg" id="mYusicLogout" /></a>');

	}	 
	   
}

function restoreLoginButtons()
{
  $('#auth').html('<h3 id="loginRegMessage">Login or register using facebook or mYusic.com</h3> <div id="userName"><a onClick="doLogin(\'fbLogin\')" href="javascript:void()"> <img style="margin:auto;" src="/DailyPosts/images/fbLogin.jpg" id="fbmYusicLogin" /></a><img src="/DailyPosts/images/slash.jpg" /><a onClick="showmYusicLoginForm()" href="javascript:void()"> <img style="margin:auto;" src="/DailyPosts/images/mLogin.jpg" id="mLogin" /> </a></div><h3 id="recoMsg">Recommendations from other mYusic users!</h3>');
}
          
function setLoggedinStatusCookie (strValue)
{

	createCookie('mYusicLoggedinStatus', strValue);
	
}

function getLoggedinStatusCookie ()
{

	if (readCookie ('mYusicLoggedinStatus')== null){
	    createCookie('mYusicLoggedinStatus', 0);
		return 0;
	}else{
	    return readCookie ('mYusicLoggedinStatus');
	}	
	
		 
}

//Name of the cookie. flagChecker indicates whether to return -1 as status for not having checked for that value ever

function getCookie(strName, flagChecker)
{
	if (readCookie (strName)== null){	    
		if (flagChecker == 1){
		    return -1;
		} else {
            createCookie(strName, 0);		    
			return 0;
		}
	}else{
	    return readCookie (strName);
	}
}

function setCookie (strName, strValue, intDays)
{
  	if (intDays) {
	  createCookie(strName, strValue, intDays);   
	} else{
	  createCookie(strName, strValue);  
	}
}

function setFriendsForeverReminder(){
  //set up the cookie to a value of 1 for 10 days!
  setCookie (DSPL_FRND_LIKE_COOKIE_NAME, 1, 10);
}



//builds a popup that dims the background and shows the popup window. if automaticFadeout = 1, it closes the popup within <Delay> seconds. Width is width of popup. left is left position. If 0 it is ignored
function buildPopup (strPopupName, automaticFadeOut, popUpWidth, popUpLeft, automaticFadeOutDelay)
{
		strCloseButtonClassName = strPopupName;        
		strPopupName = "#" + strPopupName;

		$(strPopupName).fadeIn().css({ 'width': popUpWidth }).prepend('<a href="#" class="' + strCloseButtonClassName + 'Close"><img src="/DailyPosts/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
        
        var popMargTop = ($(strPopupName).height()+ 80) / 2;
        var popMargLeft = ($(strPopupName).width()+ 80) / 2;
        
       //Apply Margin to Popup        
        if (popUpLeft == 0){
    		$(strPopupName).css({
                'margin-top' : -popMargTop,
                'margin-left' : -popMargLeft
             });
		} else if (popUpLeft != 0)
		{
    		$(strPopupName).css({
                'margin-top' : -popMargTop,
                'left' : popUpLeft
             });
		}
        
        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({'filter' : 'alpha(opacity=50)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
		        
	   if (automaticFadeOut == 1){
	           
	   	    setTimeout( function() {
		         $('#fade ,' + strPopupName).fadeOut(function() {
                     $('#fade, a.' +  strCloseButtonClassName + 'Close').remove();  //fade them both out
                     });
	        }, automaticFadeOutDelay );
       }
	   
      $('a.' + strCloseButtonClassName + 'Close').live('click', function() { //When clicking on the close or fade layer...
	      $('#fade ,' + strPopupName).fadeOut(function() {
              $('#fade, a.' +  strCloseButtonClassName + 'Close').remove();  //fade them both out
          });
          return false;
      });	   

}

//the function checks if the user has already given publish_actions permissions...If yes, publish to timeline, else popup and ask for the permission
function checkTimelinePermissions()
{
    
    		FB.api('/me/myusicf:enjoy' + 
                        '?music_station=' + $(document).find('#ogURL').attr("content"),'post',
                        function(response) {
						return false;
				});		

    		FB.api('/me/apps.uses' + 
                        '?website=http://www.myusic.com' ,'post',
                        function(response) {
						return false;
				});
				

	FB.api('/me/permissions', function(permissions){
	    if(permissions.data[0].publish_actions == 'undefined' || permissions.data[0].publish_actions == null || permissions.data[0].publish_actions == '0')
		{		    
			//Commented the statement till fb releases the timeline post beta
			//alert("dont have");
			buildPopup ("TIMELINE_MSG", 0, 600, 0, 10000);
		}else if(permissions.data[0].publish_actions == '1') {
		    
    		FB.api('/me/myusicf:enjoy' + 
                        '?music_station=' + $(document).find('#ogURL').attr("content"),'post',
                        function(response) {
						return false;
            });
    		FB.api('/me/apps.uses' + 
                        '?website=http://www.myusic.com' ,'post',
                        function(response) {
						
						return false;
				});
						   
		}		
	});
		

}

//Function to append the login & registration div to the HTML page.
$(document).ready(function() {

	var currentYear = (new Date).getFullYear();
    var checkYear = currentYear - 13;
	var strSelectYearOptions = "";
	
	for (i = currentYear; i >= 1900; i--) {
		if (i < checkYear) {
		    strSelectYearOptions = strSelectYearOptions + '<option value=' + i + '>' + i + '</option>';
		}
	}
	
    $('#selectedyear').html(strSelectYearOptions);

});



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function showError (strMessage, width){

    if (document.getElementById ('errorMsg') != null){
        $("#errorString").html(strMessage);	
    	if (width){
    	  buildPopup ("errorMsg", 0, width, 0, 0);
    	} else{
          buildPopup ("errorMsg", 0, 200, 0, 0);
    	}
	} else{
	    alert (strMessage);
	}	  
	
}


