
$(document).ready(function() {


var path='http://pyxie.me:8080/';
//var path='http://64.251.15.49:8084/';
//var path='http://192.168.1.117:8086/';
$("[data-role=panel]").panel().enhanceWithin();

$.ajaxSetup({
  xhr: function() {
    return new window.XMLHttpRequest( {
      mozSystem: true
    } );
  }
  });
 
 $('.image-link').magnificPopup({type:'image'});
 $('.test-popup-link').magnificPopup({
  type: 'image'
});

 $('.parent-container').magnificPopup({
   delegate: 'a', 
  type: 'image',
  gallery:{enabled:true}
	// other options
});

$('.parent-container2').magnificPopup({
   delegate: 'a', 
  type: 'image',
  gallery:{enabled:true}
	// other options
});
$('.parent-container3').magnificPopup({  // for instagram images
   delegate: 'a', 
  type: 'image',
  gallery:{enabled:true}
	// other options
});
$('.parent-container4').magnificPopup({ //for pinterest images
   delegate: 'a', 
  type: 'image',
  gallery:{enabled:true}
	// other options
});



 $( document ).bind( 'mobileinit', function(){
	  $.mobile.loader.prototype.options.text = "loading";
	  $.mobile.loader.prototype.options.textVisible = false;
	  $.mobile.loader.prototype.options.theme = "a";
	  $.mobile.loader.prototype.options.html = "";
	}); 
  
var mySwiper = new Swiper('.swiper-container',{
    pagination: '.pagination',
    paginationClickable: true,
    centeredSlides: true,
    slidesPerView: 2,
    watchActiveIndex: true
  });
  var mySwiper1 = new Swiper('.swiper-container1',{
    pagination: '.pagination1',
    paginationClickable: true,
    centeredSlides: true,
    slidesPerView: 2,
    watchActiveIndex: true
  });
 function showLoader(){
 
  $("#mainContent").width($(window).width()).height($(window).height());
  $("div#header").mask();
  $("div#footerNew").mask();
  $("#mainContent").mask();

	 $.mobile.loading( 'show', {
				text: 'Loading..',
				textVisible: true,
				theme: 'a',
				html: ""
				});
 } 
 function hideLoader(){
 
 $("#mainContent").width($(window).width()).height($(window).height());
  $("div#header").unmask();
  $("div#footerNew").unmask();
 $("#mainContent").unmask(); 
 $.mobile.loading( 'hide' );

 }
 
  function showOutLoader(){
 
	 $.mobile.loading( 'show', {
				text: 'Loading..',
				textVisible: true,
				theme: 'a',
				html: ""
				});
 } 
 function hideOutLoader(){

 $.mobile.loading( 'hide' );

 }
  
  var globalUserID;
  var particularPyxieId;
  //----------------------
  var iSearchCount;
  var iAlphaSearchCount;
  var iFieldSearchCount;
  //------------------------------------
  var iAllMyPCount;
  var iAlphaAllMyPCount;
  var iFieldAllMyPCount;
  //--------------------------------
  var myAlphabet;
   var allWord;
  //--------------------------------
  var searchAlpha;
  var searchWord;
  //-----------------------
  var pyxieString;  
  var specialSearch;
 //-----------------
   var max_fields      = 3; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
  //---------------------------------
  var selection;
  var uploadNewUserPic="";
  var updateOldPic="";
  var uploadPyxiePic="";
  var updatePyxiePic="";
  var pageNo;
  var fbPageNo;
  var pinPageNo;
  var bingPgno;
  var mainurl="";
 
  var offallmypyxies;
   
    $("#gotoEmailPage").click(function(event){
	 $.mobile.changePage("#email_sign_in",{ 
							          transition: "slide",
									  changeHash: false });
	});
	
	$("#gotoTwitterPage").click(function(event){
	
	if(window.navigator.onLine){
		   showLoader();
	     var number = 1 + Math.floor(Math.random() * 1000000);
            localStorage.setItem('twitterNumber',number);
			$.ajax({
						   url:path+'pyxies/userservice/rest/twitter/authentication?clientId='+localStorage.getItem('twitterNumber'),
						   type: 'GET',
			                crossDomain: true,
							  success: function(responseData, textStatus, jqXHR) 
							  {
							  console.log(responseData);							  
							   var data=jQuery.parseJSON(responseData);
							   hideLoader();
							   var new_window=window.open(data.url,"","");
		
								var interval = window.setInterval(function() {
										try {
											if (new_window == null || new_window.closed) {
												window.clearInterval(interval);
												getTwitterUserDetails(localStorage.getItem('twitterNumber'));
											}
										}
										catch (e) {
										}
									}, 500);
							   
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							   hideLoader();
								alert("Please try again after sometime!");
							  }
							});

		}
		else{
		 alert("Please Check Your Internet Connection");
		}
	
	});
	
	function getTwitterUserDetails(number){

	              showLoader();	
					$.ajax({
							   url: path+'pyxies/userservice/rest/twitter/profile?clientId='+number,
							  type: 'GET', 
							  crossDomain: true,
							  success: function(responseData, textStatus, jqXHR) 
							  {
									  console.log(responseData);
									 
									  if($.trim(responseData)!=""){
									  var obj = jQuery.parseJSON(responseData);
									   var imgurl=$.trim(obj.profile_image_url)
										var res = imgurl.replace("_normal", "");
										
									  setTwitterProfile($.trim(obj.email),obj.name,res);									
									   // hideLoader();
									  }
									  else{
									  hideLoader();
									  }
									 
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							   //hideLoader();
							  alert("Please try again after sometime!");
							  }
						 });
	}
	
	function setTwitterProfile(tEmail,tName,tImg){
	                       showLoader();
	                      var da={
								   "email" : $.trim(tEmail),
								   "name" : "",
								   "password" : "",
								   "type":"twitter"
								   };
						  var dat= JSON.stringify(da);
						  
					 $.ajax({ 
								  type: 'POST',
								  url: path+'pyxies/userservice/rest/email/registration',
								  data:dat,
								  contentType: "application/json; charset=UTF-8",
								  success: function(responseData, textStatus, jqXHR) 
								  {
						
								   var obj = jQuery.parseJSON(responseData);
								  console.log(responseData);
								  if(obj.status=="success"){
										
										 $.session.set("globalUserID",$.trim(obj.profile_data.user_id));
										 localStorage.setItem('gui', $.trim(obj.profile_data.user_id));
										 $.session.set("UserEmail",$.trim(obj.profile_data.email));
										 
										 localStorage.setItem('loginType','twitter');
										 localStorage.setItem("UserName",tName);
								        $("#profile_name").text(tName);	 
									    $('#profile_pic').css('background-image', "url("+tImg+")");
										
										getTopFivePyxiesofUser($.trim($.session.get("globalUserID")));
										$.mobile.changePage("index.html#home_page",{ 
													  transition: "fade",
													  changeHash: false });
										if($.session.get("firstLogin") != 'true'){
												   $.session.set("firstLogin",'true'); 
												   $.mobile.changePage("#How_To_Use", { 
																	  transition: "fade",
																	   changeHash: false });
										}
										  
										  setTimeout(function(){
											 hideLoader();
											}, 2500);
 
										}
									else if(obj.status=="fail"){
									   hideLoader();
									 alert(obj.error_message);
									}
								  },
								  error: function (responseData, textStatus, errorThrown) 
								   {
								       hideOutLoader();
									 alert("Please try again after sometime!");
								   }
						 });

	}
	
	$("#gotoFacebookPage").click(function(event){
	
		if(window.navigator.onLine){
		   
	     var number = 1 + Math.floor(Math.random() * 1000000);
		 
	      var new_window=window.open("https://www.facebook.com/dialog/oauth?client_id=752235481479350&response_type=token&redirect_uri="+path+"pyxies/resources/success.html?clientID="+number,"","");
		
		var interval = window.setInterval(function() {
				try {
					if (new_window == null || new_window.closed) {
						window.clearInterval(interval);
						
						getUserAccessToken(number);
					}
				}
				catch (e) {
				}
			}, 500);// intervel ended here
		}
		else{
		 alert("Please Check Your Internet Connection");
		}
	 
	});
  //-------------------------Login------------------------------------------
   
  
   $('a[id=backTop]').backTop({
                    'position' : 325,
                    'speed' : 500,
                    'color' : 'orange',
                });
				
	function getFacebookUserInfo(){
	showOutLoader();
				$.ajax({
				url:"https://graph.facebook.com/me?access_token="+localStorage.getItem('access_Token'),
				type: 'GET',				
				async:true,
				dataType : 'jsonp',
				crossDomain: true,
				success: function(responseData, textStatus, jqXHR){
				 		
						localStorage.setItem('facebook_id',responseData.id);
						
						setFacebookProfile(responseData.name,responseData.email,responseData.id);
						
				},
				error: function (responseData, textStatus, errorThrown) 
				{		
                 hideOutLoader();				
					alert("Please try again after sometime!");
				}		   
			});
	}
	
	function getUserAccessToken(number){

	              showLoader();	
					$.ajax({
							   url: path+'pyxies/userservice/rest/fbtoken/get?clientId='+number,
							  type: 'GET', 
							  crossDomain: true,
							  success: function(responseData, textStatus, jqXHR) 
							  {
									  console.log(responseData);
									 
									  if($.trim(responseData)!=""){
									  var obj = jQuery.parseJSON(responseData);
									   localStorage.setItem('access_Token', $.trim(obj.access_token));
									   localStorage.setItem('loginType', "facebook");
										
									  $.mobile.changePage("index.html#home_page",{ 
										  transition: "fade",
										  changeHash: false });
									  if($.session.get("firstLogin") != 'true'){
									   $.session.set("firstLogin",'true'); 
									   $.mobile.changePage("#How_To_Use", { 
															  transition: "fade",
															   changeHash: false });
									  }
										
									  }
									  else{
									  hideLoader();
									  }
									 
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							   //hideLoader();
							  alert("Please try again after sometime!");
							  }
						 });
	
	
       

	}

	function setFacebookProfile(fbName,fbEmail,fbId){
	                       showLoader();
	                      var da={
								   "email" : $.trim(fbEmail),
								   "name" : "",
								   "password" : "",
								   "type":"facebook"
								   };
						  var dat= JSON.stringify(da);
						  
					 $.ajax({ 
								  type: 'POST',
								  url: path+'pyxies/userservice/rest/email/registration',
								  data:dat,
								  contentType: "application/json; charset=UTF-8",
								  success: function(responseData, textStatus, jqXHR) 
								  {
						
								   var obj = jQuery.parseJSON(responseData);
								  console.log(responseData);
								  if(obj.status=="success"){
										  //alert(obj.profile_data.user_id);
										 $.session.set("globalUserID",$.trim(obj.profile_data.user_id));
										 localStorage.setItem('gui', $.trim(obj.profile_data.user_id));
										 $.session.set("UserEmail",$.trim(obj.profile_data.email));
										 localStorage.setItem('loginType', $.trim(obj.profile_data.login_type_text));
										 localStorage.setItem("UserName",fbName);
								        $("#profile_name").text(fbName);	 
									    $('#profile_pic').css('background-image', "url(https://graph.facebook.com/"+$.trim(fbId)+"/picture?type=large)");
										getTopFivePyxiesofUser($.trim($.session.get("globalUserID")));
									
										  setTimeout(function(){
											 hideLoader();
											}, 2500);
 
										}
									else if(obj.status=="fail"){
									   hideLoader();
									 alert(obj.error_message);
									}
								  },
								  error: function (responseData, textStatus, errorThrown) 
								   {
								       hideOutLoader();
									 alert("Please try again after sometime!");
								  
								   }
						 });

	}
  $(document).on("pagebeforeshow","#email_sign_in",function(){
  $("#login_email").val("");
   $("#login_password").val("");
  });
  
  $("#email_login").click(function(){
  var email = $("#login_email").val();
   var pass = $("#login_password").val();
  
  if(window.navigator.onLine){	  
		login(email,pass);							
		}
		else{
		   alert("Please Check Your Internet Connection");
		}
			
   });
   //----------------------------------------------------------Registration--------------------------------------------------------------------------
    $(document).on("pagebeforeshow","#sign_up",function(){
    $('#registration_username').val("");
    $('#registration_email').val("");
    $('#registration_password').val("");
	$('#registration_confirmpassword').val("");
	$('#agree').prop('checked', false);	
	$("#agree_image").removeClass("agree_on").addClass("agree_off");
  });
  
   $("#register").click(function(event){
   
   if(window.navigator.onLine){
	  
  var rName=$('#registration_username').val();
  var rEmail=$('#registration_email').val();
  var rPassword=$('#registration_password').val();
  var checked=$('#agree').is(':checked');
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  
  var data =rPassword;
  var len = data.length;
  
  // regex.test(rEmail)
  
  if(rName.length<1){
   alert("Name cannot be blank");
    event.preventDefault();
  }
  else if(rEmail.length<1){
  alert("Email cannot be blank");
   event.preventDefault();
  }
  else if(!regex.test(rEmail)){
  alert("Please Enter Valid Email");
   event.preventDefault();
  }else if(len < 1) {
            alert("Password cannot be blank");
            event.preventDefault();
  }else if(rPassword!= $('#registration_confirmpassword').val()) {
            alert("Password and Confirm Password don't match");
            event.preventDefault();
   }
   else if(!checked){
   alert("Please agree to the Terms and Conditions");
            event.preventDefault();
   } 
   else{
                            showOutLoader();
					      var da={
								   "email" : $.trim(rEmail),
								   "name" : $.trim(rName),
								   "password" : $.trim(rPassword),
								   "type":"email"
								   };
						  var dat= JSON.stringify(da);
						  
					 $.ajax({ 
								  type: 'POST',
								  url: path+'pyxies/userservice/rest/email/registration',
								  data:dat,
								  contentType: "application/json; charset=UTF-8",
								  success: function(responseData, textStatus, jqXHR) 
								  {
						
								   var obj = jQuery.parseJSON(responseData);
								  console.log(responseData);
								  if(obj.status=="success"){
										  
										 $.session.set("globalUserID",$.trim(obj.profile_data.user_id));
										 localStorage.setItem('gui', $.trim(obj.profile_data.user_id));
										 localStorage.setItem('loginType', $.trim(obj.profile_data.login_type_text));						 
										 $('#name_of_user').text(obj.profile_data.first_name);
										 $.session.set("UserEmail",$.trim(obj.profile_data.email));
										  hideOutLoader();
										 $("#upPic").css('display','block');
										 $("#UserCroppedImage").css('display','none');
										
										 $.mobile.changePage("index.html#upload_pic",{ 
										  transition: "fade", 
										  changeHash: false });
										}
									else if(obj.status=="fail"){
									   hideOutLoader();
									 alert(obj.error_message);
									}
								  },
								  error: function (responseData, textStatus, errorThrown) 
								   {
								       hideOutLoader();
									 alert("Please try again after sometime!");
								  
								   }
						 });
		    }		
		}//end of connectivity check
		else{
		   alert("Please Check Your Internet Connection");
		}
    
  
   });
//-----------------------------------------------------Home Page--------------------------------------------------------------------
$(document).on("pagebeforeshow","#home_page",function(){
	
	if(window.navigator.onLine){
		 $.getJSON("http://freegeoip.net/json/", function(result){
		
					   localStorage.setItem('country_code',$.trim(result.country_code));
                        });
			 var login_type=localStorage.getItem('loginType');
			 //alert($.trim(login_type));
			 if($.trim(login_type)=="facebook"){
			getFacebookUserInfo();
			 }
			 else if($.trim(login_type)=="email"){
			  //alert("in else");
			 getProfileDetails();
			 }
			 else if($.trim(login_type)=="twitter"){
			 //getTwitterUserDetails(localStorage.getItem('twitterNumber'));
			 }
		
		}
		else{
		
			
			$('#profile_pic').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('profile_back')+")");
			
			$("#profile_name").text(localStorage.getItem("UserName"));
								
			$('#first_top_pyxie').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('first_top')+")");	
			$('#first_top_pyxie_name').text(localStorage.getItem('first_top_name'));			 
			
			$('#second_top_pyxie').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('second_top')+")");									
			$('#second_top_pyxie_name').text(localStorage.getItem('second_top_name'));	
			
			$('#third_top_pyxie').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('third_top')+")");									 
			$('#third_top_pyxie_name').text(localStorage.getItem('third_top_name'));
			
			$('#forth_top_pyxie').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('forth_top')+")");
			$('#forth_top_pyxie_name').text(localStorage.getItem('forth_top_name'));
				
            $('#fifth_top_pyxie').css('background-image', "url(data:image/png;base64,"+localStorage.getItem('fifth_top')+")");
		    $('#fifth_top_pyxie_name').text(localStorage.getItem('fifth_top_name'));				
									  
		}

});
$(document).on("pageshow","#home_page",function(){
		
	if(window.navigator.onLine){
			removeids();		
			var login_type=localStorage.getItem('loginType');			
			 if($.trim(login_type)=="email"){
			 getTopFivePyxiesofUser($.trim($.session.get("globalUserID")));
			 }
			
		}
		else{
		}
		
	});
	
	function getTopFivePyxiesofUser(userID){
	//alert("userID="+userID);
                showLoader();
					  var da={
					   "userId":userID
					  };
				 var dat= JSON.stringify(da);
		  
				$.ajax({
					  type: 'POST',
					  url: path+'pyxies/pyxieservice/rest/pyxie/topfivepyxies',
					  data:dat,
					  contentType: "application/json; charset=UTF-8",
					  success: function(responseData, textStatus, jqXHR) 
					  {
					        var topFive=jQuery.parseJSON(responseData);
                              
					if($.trim(topFive)!=""){
							      $.each(topFive, function(idx, obj) {
							  console.log(idx);
									  if(idx==0)
									  {
									  $('#first_top_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									    
									   $('#first_top_pyxie').attr('data-id',obj.pyxieid);
									    var name=obj.pyxiename;
									    var charsLength = name.length;
										var newname="";
										   if(charsLength>=15)
										   {
										   for(i=0;i<12;i++){
												newname+=name[i];
												}
												newname+="...";
											$('#first_top_pyxie_name').text(newname);
										   	localStorage.setItem('first_top_name',newname);										
										   }
										   else{
										    $('#first_top_pyxie_name').text(name);
											localStorage.setItem('first_top_name',name);
										   }
										   
									   localStorage.setItem('first_top',obj.pyxieByteImage);
									   
									  }
									  else if(idx==1){
									  $('#second_top_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									
									   $('#second_top_pyxie').attr('data-id',obj.pyxieid);
									   var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=15)
										   {
										   for(i=0;i<12;i++){
												newname+=name[i];
												}
												newname+="...";
											$('#second_top_pyxie_name').text(newname);
										   	localStorage.setItem('second_top_name',newname);										
										   }
										   else{
										    $('#second_top_pyxie_name').text(name);
											localStorage.setItem('second_top_name',name);
										   }
                                     
									    localStorage.setItem('second_top',obj.pyxieByteImage);	
									   
									  } 
									  else if(idx==2){
									  $('#third_top_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									 
									  $('#third_top_pyxie').attr('data-id',obj.pyxieid);									  
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=15)
										   {
										   for(i=0;i<12;i++){
												newname+=name[i];
												}
												newname+="...";
											$('#third_top_pyxie_name').text(newname);
										   	localStorage.setItem('third_top_name',newname);										
										   }
										   else{
										    $('#third_top_pyxie_name').text(name);
											localStorage.setItem('third_top_name',name);
										   }
									  localStorage.setItem('third_top',obj.pyxieByteImage);
                                     							  
									  } 
									  else if(idx==3){
									  $('#forth_top_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");
									   $('#forth_top_pyxie').attr('data-id',obj.pyxieid);
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=15)
										   {
										   for(i=0;i<12;i++){
												newname+=name[i];
												}
												newname+="...";
											$('#forth_top_pyxie_name').text(newname);
										   	localStorage.setItem('forth_top_name',newname);										
										   }
										   else{
										    $('#forth_top_pyxie_name').text(name);
											localStorage.setItem('forth_top_name',name);
										   }

									  localStorage.setItem('forth_top',obj.pyxieByteImage);
									  
									  } 
									  else if(idx==4){
									  $('#fifth_top_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");							  
									   $('#fifth_top_pyxie').attr('data-id',obj.pyxieid);
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=15)
										   {
										   for(i=0;i<12;i++){
												newname+=name[i];
												}
												newname+="...";
											$('#fifth_top_pyxie_name').text(newname);
										   	localStorage.setItem('fifth_top_name',newname);										
										   }
										   else{
										    $('#fifth_top_pyxie_name').text(name);
											localStorage.setItem('fifth_top_name',name);
										   }									  
									  localStorage.setItem('fifth_top',obj.pyxieByteImage);
									
									  }
							 
						   });
						}
							
						   
							setTimeout(function(){
							 hideLoader();
							}, 3000);
					  },
					  error: function (responseData, textStatus, errorThrown) 
					  {
					   hideLoader();
					  alert("Please try again after sometime!");
					  }
				 });
		  }
		  
$(document).on('vclick', 'table[id=topFivetable] tr td div[id=openTopFive] div div div', function(){
	var pId=$.trim($(this).attr('data-id'));
	
	if(window.navigator.onLine){
		      if(pId==""){   
					alert("Currently you dont have this Pyxie available.Please create a new pyxie!");
					}
					else{
                    localStorage.setItem('prefScreen','3');					
					openPyxie(pId);
					}
		}
		else{
		alert("Please Check Your Internet Connection");
		}
	
});

$(document).on("pageshow","#add_pyxies",function(){
//put here
  showLoader();
 $("#world").trigger('click');
 setTimeout(function(){
				hideLoader();
				}, 3000);
});

$("#world").click(function(){
      //put here
	 $("#world").removeClass("wc_off").addClass("wc_on");
 $("#country").removeClass("wc_on").addClass("wc_off"); 
	  showLoader();
removeCountryWorld();
				$.ajax({
				       url: path+'pyxies/pyxieservice/rest/pyxie/top5pyxiesbyworld',
					  type: 'GET', 
					  crossDomain: true,
					  success: function(responseData, textStatus, jqXHR) 
					  {
					           // console.log(responseData);
					        var topFive=jQuery.parseJSON(responseData);
                        setWorldCountry(topFive);

							setTimeout(function(){
							 hideLoader();
							}, 3000);
					  },
					  error: function (responseData, textStatus, errorThrown) 
					  {
					   hideLoader();
					  alert("Please try again after sometime!");
					  }
				 });

});
$("#country").click(function(){
//put here
        $("#country").removeClass("wc_off").addClass("wc_on"); 
 $("#world").removeClass("wc_on").addClass("wc_off"); 
            showLoader();
    removeCountryWorld();
				$.ajax({
				       url: path+'pyxies/pyxieservice/rest/pyxie/top5pyxiesbycountry?location='+localStorage.getItem('country_code'),
					  type: 'GET', 
					  crossDomain: true,
					  success: function(responseData, textStatus, jqXHR) 
					  {
					           // console.log(responseData);
					        var topFive=jQuery.parseJSON(responseData);
                        setWorldCountry(topFive);

							setTimeout(function(){
							 hideLoader();
							}, 3000);
					  },
					  error: function (responseData, textStatus, errorThrown) 
					  {
					   hideLoader();
					  alert("Please try again after sometime!");
					  }
				 });
});
function setWorldCountry(topFive){

						   
$.each(topFive, function(idx, obj) {
							  console.log(idx);
									  if(idx==0)
									  {
									  $('#first_country_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									    
									   $('#first_country_pyxie').attr('data-id',obj.pyxieid);
									    var name=obj.pyxiename;
									    var charsLength = name.length;
										var newname="";
										   if(charsLength>=9)
										   {
										   for(i=0;i<8;i++){
												newname+=name[i];
												}
												newname+="..";
											$('#first_country_pyxie_name').text(newname);
										   									
										   }
										   else{
										    $('#first_country_pyxie_name').text(name);
											
										   }

									  }
									  else if(idx==1){
									  $('#second_country_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									
									   $('#second_country_pyxie').attr('data-id',obj.pyxieid);
									   var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=9)
										   {
										   for(i=0;i<8;i++){
												newname+=name[i];
												}
												newname+="..";
											$('#second_country_pyxie_name').text(newname);
										   									
										   }
										   else{
										    $('#second_country_pyxie_name').text(name);
											
										   }

									  } 
									  else if(idx==2){
									  $('#third_country_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");									 
									  $('#third_country_pyxie').attr('data-id',obj.pyxieid);									  
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=9)
										   {
										   for(i=0;i<8;i++){
												newname+=name[i];
												}
												newname+="..";
											$('#third_country_pyxie_name').text(newname);
										   										
										   }
										   else{
										    $('#third_country_pyxie_name').text(name);
											
										   }
						  
									  } 
									  else if(idx==3){
									  $('#forth_country_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");
									   $('#forth_country_pyxie').attr('data-id',obj.pyxieid);
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=9)
										   {
										   for(i=0;i<8;i++){
												newname+=name[i];
												}
												newname+="..";
											$('#forth_country_pyxie_name').text(newname);
										   										
										   }
										   else{
										    $('#forth_country_pyxie_name').text(name);
											
										   }
									  } 
									  else if(idx==4){
									  $('#fifth_country_pyxie').css('background-image', "url(data:image/png;base64,"+ obj.pyxieByteImage+")");							  
									   $('#fifth_country_pyxie').attr('data-id',obj.pyxieid);
									  var name=obj.pyxiename;
                                       var charsLength = name.length;
										var newname="";
										   if(charsLength>=9)
										   {
										   for(i=0;i<8;i++){
												newname+=name[i];
												}
												newname+="..";
											$('#fifth_country_pyxie_name').text(newname);
										   										
										   }
										   else{
										    $('#fifth_country_pyxie_name').text(name);
											
										   }									  
									  }							 
						   });


}
$(document).on('vclick', 'table[id=topCountrytable] tr td div[id=openCountryFive] div div div', function(){
	var pId=$.trim($(this).attr('data-id'));
	
	if(window.navigator.onLine){
		      if(pId==""){   
					alert("Currently you dont have this Pyxie available.Please create a new pyxie!");
					}
					else{	
                    localStorage.setItem('prefScreen','4');					
					openPyxie(pId);
					}
		}
		else{
		alert("Please Check Your Internet Connection");
		}
	
});	
	  
function openPyxie(pyxieid){
	showOutLoader();
	
	/*$.ajax({ 
			url:path+"pyxies/pyxieservice/rest/pyxie/settingsInfo?pyxieId="+$.trim(pyxieid),
			type: 'GET',
			crossDomain: true,
			success: function(responseData, textStatus, jqXHR) 
			{
				
				var i;
				var data=jQuery.parseJSON(responseData);
				var mediaIds=data.mediaIds;
				console.log(mediaIds);
				
				$('#googleImagesTab').disable(true); 
                $('#pinterestImagesTab').disable(true); 
				$('#flickrImagesTab').disable(true); 
				$('#youtubeVideoTab').disable(true); 
				$('#vimeoVideoTab').disable(true); 
				$('#facebookSocialTab').disable(true); 
				$('#twitterSocialTab').disable(true); 
				$('#gplusSocialTab').disable(true); 
				$('#instagramSocialTab').disable(true); 
				$('#timeNewsTab').disable(true); 
				$('#cnnNewsTab').disable(true); 
				$('#bbcNewsTab').disable(true); 
				$('#googleNewsTab').disable(true); 
				$('#imdbTab').disable(true); 
				$('#bingTab').disable(true); 
				$('#wikipediaTab').disable(true); 
				$('#amazonTab').disable(true);
				
				var arr=mediaIds.split(",");
				for(i=0;i<arr.length;i++){
					if(arr[i]!=""){
							//switchImageCase(arr[i]);
							}
					}
			},
			error: function (responseData, textStatus, errorThrown) 
			{
				hideLoader();
				alert("Please Try again after sometime");
			}
		});*/
	
	var da={
		    "pyxieId":pyxieid
		  };
		var dat= JSON.stringify(da);		
		    $.ajax({
							  type: 'POST',
							  url: path+'pyxies/pyxieservice/rest/pyxie/pyxieview',
							  data:dat,
							  contentType: "application/json; charset=UTF-8",
							  success: function(responseData, textStatus, jqXHR) 
							  {
							    console.log(responseData);
							  var data=jQuery.parseJSON(responseData);
                               hideLoader();							  
							   executePyxieInfo(data);	
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
							  alert("Please try again after sometime!");
							  }
					  });
					  
}

/*jQuery.fn.extend({
        disable: function(state) {
            return this.each(function() {
                var $this = $(this);
                if($this.is('a'))
                    this.disabled = state;
                else
                    $this.toggleClass('disabled', state);
            });
        }
    });*/
/*function switchImageCase(no){
alert(no);
		switch(no){ 
		
		        case "1":day = $('#googleImagesTab').disable(false); 
                      		   //$("#google_image_up").addClass("google_on");		
				break;
				case "2":day = $('#pinterestImagesTab').disable(false); 
					          // $("#pinterest_image_up").addClass("pinterest_on");
				break;
				case "3":day = $('#flickrImagesTab').disable(false); 
				 	         // $("#flickr_image_up").addClass("flickr_on");
				break;
				case "4":day = $('#youtubeVideoTab').disable(false); 
					//$("#youtube_image_up").addClass("youtube_on"); 
				break;
				case "5":day = $('#vimeoVideoTab').disable(false); 
				     //$("#vimeo_image_up").addClass("vimeo_on");
				break;
				case "6":day = $('#facebookSocialTab').disable(false); 
					//$("#facebook_image_up").addClass("facebook_on");
				break;
				case "7":day = $('#twitterSocialTab').disable(false); 
				 	//$("#twitter_social_image_up").addClass("twitter_on");
				break;
				case "8":day = $('#gplusSocialTab').disable(false); 
				    //$("#google_plus_image_up").addClass("google_plus_on");
				break;
				case "9":day = $('#instagramSocialTab').disable(false); 
				 	//$("#instagram_image_up").addClass("instagram_on");
				break;
				case "10":day = $('#timeNewsTab').disable(false); 
				 	//$("#times_image_up").addClass("times_on"); 
				break;
				case "11":day = $('#cnnNewsTab').disable(false); 
					//$("#cnn_image_up").addClass("cnn_on");
				break;
				case "12":day = $('#bbcNewsTab').disable(false); 
				 	//$("#bbc_image_up").addClass("bbc_on");
				break;
				case "13":day = $('#googleNewsTab').disable(false); 
					//$("#google_news_image_up").addClass("google_news_on");
				break;
				case "14":day = $('#imdbTab').disable(false); 
					//$("#imdb_image_up").addClass("imdb_on");
				break;
				case "15":day = $('#bingTab').disable(false); 
				 	//$("#bing_image_up").addClass("bing_on"); 
				break;
				case "16":day = $('#wikipediaTab').disable(false); 
					//$("#wikipedia_image_up").addClass("wikipedia_on"); 
				break;
				case "17":day = $('#amazonTab').disable(false); 
				    
				break;
				case "18":
				    
				break;
				
		        
		}
}	*/

//-----------------------------------------------------------All My Pyxies----------------------------------------------------------------------------	

$(document).on("pagebeforeshow","#all_my_pyxies",function(){
	iAllMyPCount=0;
  iAlphaAllMyPCount=0;
  iFieldAllMyPCount=0;
   $('#allMyPyxiesList').empty();
	});	 
$(document).on("pageshow","#all_my_pyxies",function(){
	//alert("all my pyxies");
	if(window.navigator.onLine){
	  getMyListOfPyxies(iAllMyPCount);
	}
	else{
	var got=localStorage.getItem("offallmypyxies");
	//alert(got);
	  $.each(got, function(idx, obj) {					
					$('#allMyPyxiesList').append('<li data-icon="false"><a href="" id="eachMyPyxie" data-id="' + obj.pyxieid + '" class="transparentList"><div class="small-hexagon small-hexagon1"><div class="small-hexagon-in1"><div class="small-hexagon-in2" style="background-image: url(data:image/png;base64,' + obj.pyxieByteImage + ');"></div></div></div><p style="float:right;padding-left:25%;position: absolute;margin-top: -12%;color:white;">'+ obj.pyxiename + '</p></a></li>');
			});
					$('#allMyPyxiesList').listview('refresh');
	}
});
	
function getMyListOfPyxies(ampiCount){
$('#searchMyPyxieField').val("");
   showLoader();
  
	 var da={
			   "userId":$.trim($.session.get("globalUserID")),
			   "indexCount":ampiCount
			  };
         var dat= JSON.stringify(da); 
	    $.ajax({
			  type: 'POST',
			  url: path+'pyxies/pyxieservice/rest/pyxie/allmypyxies',
			  data:dat,
			  contentType: "application/json; charset=UTF-8",
			  success: function(responseData, textStatus, jqXHR) 
			  {
			     if(ampiCount==0){
					$('#allMyPyxiesList').empty();
				}
					   localStorage.setItem('AMP',JSON.stringify(responseData));
			   var allMyPyxies=jQuery.parseJSON(responseData);
			   if(ampiCount==0 && allMyPyxies.length==0){
					  hideLoader();
					 alert("No Pyxie Found!! You can create your own pyxie!!");
					 }
			       else if(allMyPyxies.length==0){
			          hideLoader();
						 alert("No More Pyxies");
						}
						else{
								
					 validateAllMyPyxies(allMyPyxies,1);
				 }

			  },
			  error: function (responseData, textStatus, errorThrown) 
			  {
			   hideLoader();
			  alert("Please try again after sometime!");
			  }
         });
	
	}
	
	//--------------------------------indexed search for all my Pyxies-------------------------
	$(document).on('vclick', '#alphalist li', function(){
	//put here
	     
		   iAlphaAllMyPCount=0;//when user click on alphabet(or new alphabet) the index should start from 0 for each alphabet.
			showLoader();
			myAlphabet=$(this).attr('data-id');
			
			getAllParticularIndexedPyxies(myAlphabet,iAlphaAllMyPCount);

	}); 
	
	function getAllParticularIndexedPyxies(alpha,count){
					  
	   var da={
			               
					"userId":$.trim($.session.get("globalUserID")),
					"title": alpha,
					"indexCount":count

				  };
				  var dat= JSON.stringify(da);
				  
					 $.ajax({ 
						  type: 'POST',
						  url: path+'pyxies/pyxieservice/rest/pyxie/searchMyPyxieStartingWith',
						  data:dat,
						  contentType: "application/json; charset=UTF-8",
						  success: function(responseData, textStatus, jqXHR) 
						  {
						  
								  if(count==0){
									$('#allMyPyxiesList').empty();
								}
									  
							   var allMyPyxies=jQuery.parseJSON(responseData);
							   if(count==0 && allMyPyxies.length==0){
									  hideLoader();
									 alert("No Pyxie Found!! You can create your own pyxie!!");
									 iAllMyPCount=0;
									 getMyListOfPyxies(iAllMyPCount);
									 }
								   else if(allMyPyxies.length==0){
									  hideLoader();
										 alert("No More Pyxies");
										 //getMyListOfPyxies();
										}
										else{
												/*$.each(allMyPyxies, function(idx, obj) {					
												$('#allMyPyxiesList').append('<li data-icon="false"><a href="" data-id="' + obj.pyxieid + '" class="transparentList"><img style="margin:5px;" height="45px" width="45px" src="data:image/png;base64,'+obj.pyxieByteImage+'"/><p style="font-style:normal;color:#fff;">'+ obj.pyxiename + '</p></a></li>');
													});*/
									 validateAllMyPyxies(allMyPyxies,2);
								 }				 
						  },
						  error: function (responseData, textStatus, errorThrown) 
						  {
						  hideLoader();
						 alert("Please try again after sometime!");
						  }
				 });
	}
	  //----------------------------open pyxie from all my pyxies------------------------------
	$(document).on('vclick', '#allMyPyxiesList li[id!=loadAllMyP] a[id=eachMyPyxie]', function(){  
    
	//alert($(this).attr('data-id'));
	  var pId=$.trim($(this).attr('data-id'));
	  //alert(pId);    
	  if(window.navigator.onLine){

	  localStorage.setItem('prefScreen','2');
				 openPyxie(pId);				
		}
		else{
		   alert("Please Check Your Internet Connection");
		}
   });
     //--------------------------------------------normal search for all my pyxies(search field)-------------------------------	

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();



$('#searchMyPyxieField').keyup(function() {
    delay(function(){     
	  iFieldAllMyPCount=0;
       showLoader();
		 allWord=$('#searchMyPyxieField').val();
		//alert(dynamicValue);
		if(window.navigator.onLine){
	     getAllMySearchFieldPyxies(allWord,iFieldAllMyPCount);								
		}
		else{
		   alert("Please Check Your Internet Connection");
		}
		
		$('#searchMyPyxieField').blur();
    }, 2000 );
});	 
      
		
	function getAllMySearchFieldPyxies(dynamicValue,count){ 
	       
	  if(dynamicValue!=""){
					   var da={
					           "userId":$.trim($.session.get("globalUserID")),
                               "title":dynamicValue,
                               "indexCount":count 
							 };
					   var dat= JSON.stringify(da);
								$.ajax({
								  type: 'POST',
								  url: path+'pyxies/pyxieservice/rest/pyxie/searchMyPyxie',
								  data:dat,
								  contentType: "application/json; charset=UTF-8",
								  success: function(responseData, textStatus, jqXHR) 
								  {
                                  if(count==0){
				                       $('#allMyPyxiesList').empty();
				                       }								  
  
							         var allMyPyxies=jQuery.parseJSON(responseData);
							           if(count==0 && allMyPyxies.length==0){
											  hideLoader();
											 alert("No Pyxie Found!! You can create your own pyxie!!");
											 iAllMyPCount=0;
                                              getMyListOfPyxies(iAllMyPCount);
									    }
								      else if(allMyPyxies.length==0){
											  hideLoader();
												 alert("No More Pyxies");
												 //getMyListOfPyxies();
										}
										else{
												/*$.each(allMyPyxies, function(idx, obj) {					
												$('#allMyPyxiesList').append('<li data-icon="false"><a href="" data-id="' + obj.pyxieid + '" class="transparentList"><img style="margin:5px;" height="45px" width="45px" src="data:image/png;base64,'+obj.pyxieByteImage+'"/><p style="font-style:normal;color:#fff;">'+ obj.pyxiename + '</p></a></li>');
													});*/
									      validateAllMyPyxies(allMyPyxies,3);
								      }
									   
								  },  
								  error: function (responseData, textStatus, errorThrown) 
								  {
								  hideLoader();
								   alert("Please try again after sometime!");
								  }
							 });
					   }
					   else{
						  iAllMyPCount=0; //if the search box becomes empty again after typying.show all the pyxies
						  getMyListOfPyxies(iAllMyPCount);
					   }
					   
	}
		
		
$(document).on('vclick', '#allMyPyxiesList li[id=loadAllMyP]', function(){
//put here
		 $(this).remove();
		 var k=$.trim($(this).attr('data-id'));
		 if(k==1){
		 getMyListOfPyxies(iAllMyPCount);
		 }
		 else if(k==2){
		 getAllParticularIndexedPyxies(myAlphabet,iAlphaAllMyPCount);
		 }
		 else if(k==3){
		 getAllMySearchFieldPyxies(allWord,iFieldAllMyPCount);
		 }
  
});
		
function validateAllMyPyxies(allMyPyxies,type){
          
			localStorage.setItem("offallmypyxies",allMyPyxies);
                   $.each(allMyPyxies, function(idx, obj) {					
						$('#allMyPyxiesList').append('<li data-icon="false"><a href="" id="eachMyPyxie" data-id="' + obj.pyxieid + '" class="transparentList"><div class="small-hexagon small-hexagon1"><div class="small-hexagon-in1"><div class="small-hexagon-in2" style="background-image: url(data:image/png;base64,' + obj.pyxieByteImage + ');"></div></div></div><p style="float:right;padding-left:25%;position: absolute;margin-top: -12%;color:white;">'+ obj.pyxiename + '</p></a></li>');
					});
	 if(allMyPyxies.length>=20){
						$('#allMyPyxiesList').append('<li id="loadAllMyP" data-icon="false" ><a href="#" data-role="button" data-mini="true"><p align="center" style="color:#000;font-size:15px;">Load More<p></a></li>');
						$('#allMyPyxiesList').listview('refresh');
						if(type==1){
							 iAllMyPCount=iAllMyPCount+20;
							  $('#loadAllMyP').attr('data-id',1);
						}
						else if(type==2){
							 iAlphaAllMyPCount=iAlphaAllMyPCount+20;
							 $('#loadAllMyP').attr('data-id',2);
						}
						else if(type==3){
							iFieldAllMyPCount=iFieldAllMyPCount+20;
							$('#loadAllMyP').attr('data-id',3);
						}
						
					}
					else{
					  $('#allMyPyxiesList').listview('refresh');
			         }
			hideLoader();
	}
//------------------------------------------------------End Of All My Pyxies-------------------------------------------------------------------------------------

//--------------------------------------------------------Search Pyxie------------------------------------------------------------------------------------------
	$(document).on("pagebeforeshow","#search_pyxie",function(){
	iSearchCount=0;
	iAlphaSearchCount=0;
	iFieldSearchCount=0;
	 $('#searchList').empty();
	
	});
	
    $(document).on("pageshow","#search_pyxie",function(){
		//put here
		getSearchListOfPyxies(iSearchCount);
			  
	});
     //-----------------------------get the search List of pyxies--------------------------------
	function getSearchListOfPyxies(indexCnt){
	
	$('#searchPyxieField').val("");
	showLoader();
	//alert("getSearchListcalled");
	
	    var da={
                 "userid":$.trim($.session.get("globalUserID")),
                 "indexCount":indexCnt
                 };
		var dat= JSON.stringify(da);
		
		$.ajax({
			  type: 'POST',
			  url: path+'pyxies/pyxieservice/rest/pyxie/searchAllPyxies',
			  data:dat,
			  contentType: "application/json; charset=UTF-8",
			  success: function(responseData, textStatus, jqXHR) 
			  { 
			  if(indexCnt==0){
				 $('#searchList').empty();
			}
			         
					 var searchList=jQuery.parseJSON(responseData);
					 if(indexCnt==0 && searchList.length==0){
					  hideLoader();
					 alert("No Pyxie Found!! You can create your own pyxie!!");
					 }
					 else if(searchList.length==0){
					 hideLoader();
					 alert("No More Pyxies");
					 }
					 else{
					    
						validateSearchPyxies(searchList,1);
					 }
			  },  
			  error: function (responseData, textStatus, errorThrown) 
			  {
			  hideLoader();
			  alert("Please try again after sometime!");
			  }
         });
	}
	
	
	//-----------------------------opening pyxie from search list-----------------------------
	$(document).on('vclick', '#searchList li[id!=loadmore] a[id=eachPyxie]', function(){
	       
			var pId=$.trim($(this).attr('data-id'));
			if(window.navigator.onLine){
			
	         localStorage.setItem('prefScreen','1');
			 
				openPyxie(pId);				
				}
				else{
				   alert("Please Check Your Internet Connection");
				}
            
			
	});
	//-------------------------------------Add this Pyxie to all my pyxies------------------------------------
	$(document).on('vclick', '#searchList li a[id=addPyxieButton]', function(){
	//put here
			var splitData=$(this).attr('data-id');
			var arr=splitData.split(" ");
			var pyxieID=$.trim(arr[0]);
			var PublisherID=$.trim(arr[1]);
			//alert(pyxieID+" "+PublisherID+" "+$.trim($.session.get("globalUserID")));
			var da={
				  "pyxieId": pyxieID,
				  "publisherId": PublisherID,
				  "subscriberId": $.trim($.session.get("globalUserID"))				  
				};
		   var dat= JSON.stringify(da);
		   
		   $.ajax({
			  type: 'POST',
			  url: path+'pyxies/pyxieservice/rest/pyxie/addthispyxie',
			  data:dat,
			  contentType: "application/json; charset=UTF-8",
			  success: function(responseData, textStatus, jqXHR) 
			  {			
			    var resultJson=jQuery.parseJSON(responseData);
			 			alert(resultJson.result);
			  },  
			  error: function (responseData, textStatus, errorThrown) 
			  {
			  alert("Please try again after sometime!");
			  }
         });
			
			
	});
	
	//-------------------------search pyxies by index(ALPHABETS)--------------------------
	$(document).on('vclick', '#alphasearchlist li', function(){
	        //alert("in search:"+$(this).attr('data-id'));
			iAlphaSearchCount=0;
			showLoader();
			 searchAlpha=$(this).attr('data-id');
			 
			 if(window.navigator.onLine){	  
				 getSearchParticularIndexedPyxies(searchAlpha,iAlphaSearchCount);				
				}
				else{
				   alert("Please Check Your Internet Connection");
				}


	});
	function getSearchParticularIndexedPyxies(alpha,cnt){
		
	           var da={
						   "userId":$.trim($.session.get("globalUserID")),
						   "title": alpha,
						  "indexCount":cnt
						   
				  };
				  var dat= JSON.stringify(da); 
					 $.ajax({ 
					 type: 'POST',
				  url: path+'pyxies/pyxieservice/rest/pyxie/searchPyxieStartingWith',
				  data:dat,
				  contentType: "application/json; charset=UTF-8",
				  success: function(responseData, textStatus, jqXHR) 
				  {
				  if(cnt==0){	 
				  $('#searchList').empty();
				 }

			          var searchList=jQuery.parseJSON(responseData);
					  if(cnt==0 && searchList.length==0){
									  hideLoader();
									 alert("No Pyxie Found!! You can create your own pyxie!!");
						iSearchCount=0;
					   getSearchListOfPyxies(iSearchCount);
									 
					}
					else if(searchList.length==0){
									  hideLoader();
										 alert("No More Pyxies");
										//iSearchCount=0;
						                //getSearchListOfPyxies(indexCount);
					}
					else{
									
							validateSearchPyxies(searchList,2);
					}
					 
				  },
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				  alert("Please try again after sometime!");
				  }
				 });
	
	}
	//---------------------------------loadmore pyxies-------------------	
	$(document).on('vclick', '#searchList li[id=loadmore]', function(){
	    //put here
		   $(this).remove();
            //  showLoader();
		 var k=$.trim($(this).attr('data-id'));
		 if(k==1){
		 getSearchListOfPyxies(iSearchCount);
		 }
		 else if(k==2){
		 getSearchParticularIndexedPyxies(searchAlpha,iAlphaSearchCount);
		 }
		 else if(k==3){
		 getSearchFieldPyxies(searchWord,iFieldSearchCount);
		 }
		 
	});	
	
	//------------------search pyxies from search field-------------------------------
	
	$('#searchPyxieField').keyup(function() {
    delay(function(){     
	 iFieldSearchCount=0;
      showOutLoader();
	searchWord=$('#searchPyxieField').val();
 
   if(window.navigator.onLine){
	  
	 getSearchFieldPyxies(searchWord,iFieldSearchCount);			
		}
		else{
		   alert("Please Check Your Internet Connection");
		}
   $('#searchPyxieField').blur();
    }, 1000 );
  });	
		function getSearchFieldPyxies(dynamicValue,cnt){
		
		 if(dynamicValue!="")
					   {
					   var da={
							"userId":$.trim($.session.get("globalUserID")),
							 "title": dynamicValue,
							 "indexCount":cnt
							 };
					   var dat= JSON.stringify(da);
								$.ajax({
								  type: 'POST',
								  url: path+'pyxies/pyxieservice/rest/pyxie/searchPyxie',
								  data:dat,
								  contentType: "application/json; charset=UTF-8",
								  success: function(responseData, textStatus, jqXHR) 
								  {
								  if(cnt==0){
		                            $('#searchList').empty();
		                                }

								   var searchList=jQuery.parseJSON(responseData);
								   if(cnt==0 && searchList.length==0){
									  hideOutLoader();
									 alert("No Pyxie Found!! You can create your own pyxie!!");
									 iSearchCount=0;
					                 getSearchListOfPyxies(iSearchCount);
									 }
								   else if(searchList.length==0){
								   hideOutLoader();
			                                alert("No Pyxie Found");
											//iSearchCount=0;
						                    //getSearchListOfPyxies(iSearchCount);
			                           }
									   else{
									           validateSearchPyxies(searchList,3);
									}
								  },  
								  error: function (responseData, textStatus, errorThrown) 
								  {
								  hideOutLoader();
								  alert("Please try again after sometime!");

								  }
							 });
					   }
					   else{
					   iSearchCount=0;
					   getSearchListOfPyxies(iSearchCount);//calling all the pyxies if the search box is empty again
					   }
		}
		
		function validateSearchPyxies(searchList,type){// disabling load more button if the records are less than twenty
		
		      $.each(searchList, function(idx, obj) {
					$('#searchList').append('<li><a href="" id="eachPyxie" data-id="' + obj.pyxieid + '"  class="transparentList"><div class="small-hexagon small-hexagon1"><div class="small-hexagon-in1"><div class="small-hexagon-in2" style="background-image: url(data:image/png;base64,' + obj.pyxieByteImage + ');"></div></div></div><p style="float:right;padding-left:25%;position: absolute;margin-top: -12%;color:white;">'+ obj.pyxiename + '</p></a><a href="#"  data-theme="false" data-role="button" id="addPyxieButton" data-id="' + obj.pyxieid+" "+obj.userid +'"  style="border:0px;margin-top: 15px;" data-icon="customicon" class="transparentList"></a></li>');
				});
			
	      if(searchList.length>=20){
						$('#searchList').append('<li id="loadmore" data-icon="false" ><a href="#" data-role="button" data-mini="true"><p align="center" style="color:#000;font-size:15px;">Load More<p></a></li>');
						$('#searchList').listview('refresh');
						if(type==1){
							 iSearchCount=iSearchCount+20;
							  $('#loadmore').attr('data-id',1);
						}
						else if(type==2){
							 iAlphaSearchCount=iAlphaSearchCount+20;
							 $('#loadmore').attr('data-id',2);
						}
						else if(type==3){
							iFieldSearchCount=iFieldSearchCount+20;
							$('#loadmore').attr('data-id',3);
						}
					}
					else{
					  $('#searchList').listview('refresh');
			         }
					hideLoader();
		}
  
//------------------------------------------------END OF SEARCH PYXIES-------------------------------------------------------------------------------------------	
	$('#home_page_edit_button').on('click', function(){
	var login_type=localStorage.getItem('loginType');
			
			 if($.trim(login_type)=="facebook"){
			 alert("Editing not available for facebook");
			 }
             else if($.trim(login_type)=="twitter"){
			 alert("Editing not available for twitter");
              }			 
			 else{
			     if(window.navigator.onLine){
	  
					 $("#updateProPic").css('display','block');
					 $("#updateCroppedImage").css('display','none');
					 getProfileDetails();
					 
					 $.mobile.changePage("index.html#profile_settings",{ 
										  transition: "slide"
										, changeHash: false });							
					}
					else{
					   alert("Please Check Your Internet Connection");
					}
			 }
	  					
	});
	$(document).on("pagebeforeshow","#change_password",function(){
			//alert("profile setting");
			   		 
			$("#current_pasword").val("");
			$("#new_pasword").val("");
			$("#con_pasword").val("");
	});
	function getProfileDetails(){
	
	                    showOutLoader();
						
						
		
						var formData=new FormData();
                       var gui= $.trim($.session.get("globalUserID"));						
						formData.append('userId',gui);
					   $.ajax({
					  url:path+'pyxies/userservice/profile',
					  type: 'POST',
					  data: formData,
					  processData: false,
					  contentType: false,
						   success: function(responseData, textStatus, jqXHR){
								console.log(responseData);
								var User=jQuery.parseJSON(responseData);
								 $.session.set("UserEmail",$.trim(User.emailId));
								 localStorage.setItem("UserName",User.fname);
								$("#profile_name").text(User.fname);
								  $('#edit_username').val(User.fname);
								  $('#edit_email').val(User.emailId);
								  setProfileImage(User);
								hideOutLoader();
							},
							 error: function (responseData, textStatus, errorThrown) 
							{
							  hideOutLoader();
							 alert("Please try again after sometime!");
							 }
				   
				   });
	
	}
//--------------------------------------Uploading and Updating images----------------------------------------------
	
//------------------------------------End of Updating and Uploading-------------------------------------------------
	
	
$("#continueButton").click(function(){

/*var f=$("input[type=file][id=image]").val();
if(f==""){
alert("Please Upload a picture"); 
}else{*/
//put here
if(uploadNewUserPic==""){
   alert("Please select A Profile Picture");
}
else{
                  showOutLoader();
				var formData=new FormData(document.forms.namedItem("fileinfo"));
				formData.append('userId', $.trim($.session.get("globalUserID")));
			  formData.append('file', uploadNewUserPic);
			   $.ajax({
			  url:path+'pyxies/userservice/pic/upload',
			  type: 'POST',
			  data: formData,
			  processData: false,
			  contentType: false,
				   success: function(responseData, textStatus, jqXHR){
						var newUser=jQuery.parseJSON(responseData);	
                        $.trim($.session.get("globalUserID"));								
						setProfileImage(newUser);
                          $("#profile_name").text(newUser.fname);
                            hideOutLoader();						  
						$.mobile.changePage("index.html#How_To_Use",{ 
							  transition: "fade"
							  , changeHash: false });						
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				   hideOutLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });

     }
                   
});
    
   
  $("#edit_button").click(function(){
  //put here
  showOutLoader();
  
   var uname=$("#edit_username").val();
   var uemail=$("#edit_email").val();
		if(updateOldPic==""){
		
		    var formData=new FormData();				
				formData.append('userId',$.trim($.session.get("globalUserID")));
				formData.append('name',uname);
				formData.append('email',uemail);
			   $.ajax({
			  url:path+'pyxies/userservice/update_profile_without_pic',
			  type: 'POST',
			  data: formData,
			  processData: false,
			  contentType: false,
				   success: function(responseData, textStatus, jqXHR){
						var User=jQuery.parseJSON(responseData);
						$("#profile_name").text(User.fname);
						 $.session.set("UserEmail",$.trim(User.emailId));						
						   hideOutLoader();
						$.mobile.changePage("index.html#home_page",{ 
							  transition: "slide", 
							   reverse: true,
							  changeHash: false });
					},
				error: function (responseData, textStatus, errorThrown) 
				  {
				  hideOutLoader();
				  alert("Please try again after sometime!");
				  }
		   
		   });
		}else{
				var formData=new FormData();				
				formData.append('userId',$.trim($.session.get("globalUserID")));
				formData.append('name',uname);
				formData.append('email',uemail);
			    formData.append('file',updateOldPic);

			   $.ajax({
			  url:path+'pyxies/userservice/update_profile',
			  type: 'POST',
			  data: formData,
			  processData: false,
			  contentType: false,
				   success: function(responseData, textStatus, jqXHR){

						var User=jQuery.parseJSON(responseData);
						updateOldPic="";
						$("#profile_name").text(User.fname);
					    $.session.set("UserEmail",$.trim(User.emailId));
						
						setProfileImage(User);						
						   hideLoader();
						$.mobile.changePage("index.html#home_page",{ 
							  transition: "slide", 
							   reverse: true,
							  changeHash: false });
					},
				error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }
		   
		   });
        }
 
   });
   
   function setProfileImage(jsonObj){
   
			//$('#background_home').css('background-image',  "url(data:image/png;base64,"+ jsonObj.image+")");
			$('#profile_pic').css('background-image', "url(data:image/png;base64,"+ jsonObj.image+")");
			localStorage.setItem('profile_back',jsonObj.image);
			 //$('#profile_pic').attr('src',  "data:image/png;base64,"+jsonObj.image);
   }
	

 //------------------------------Select Sources-------------------------------------------------------------------------
	 $("#logout").click(function(){
 $.mobile.page.prototype.options.domCache = false;
 var logtype=localStorage.getItem('loginType');

	 if(logtype=="facebook"){
	 window.open("https://www.facebook.com/logout.php?next="+path+"pyxies/resources/success.html?clientID=&access_token="+localStorage.getItem('access_Token'),"","");	 
	 localStorage.setItem('access_Token','');
	 localStorage.setItem('facebook_id',"");   	 
	 }
	 else if(logtype=="twitter"){
	
	 var  my1Window = window.open("https://twitter.com/logout", "", "");
                 setTimeout(function(){				
					my1Window.close();						
					}, 5000);
	 }
	 
	$.session.set("globalUserID","");
	localStorage.setItem('gui',"");	
	 localStorage.setItem('loginType','');
	localStorage.setItem('prefScreen','');
	localStorage.setItem('country_code','');
	
	
	 $.mobile.changePage("index.html#social_page",{ 
						  transition: "slide", 
						  changeHash: true 
						  });
	location.reload();	
	 });
$(document).on("pageshow","#social_page",function(){
 loadBundles($.i18n.browserLang());
 var seleted=$.trim(localStorage.getItem('language'));
  loadBundles(seleted !== 'browser' ? seleted : $.i18n.browserLang());
 /*alert(seleted);
	 if(seleted==""){
	
	 }
	 else{
	 }*/
});


$("a[id=goBackToScreen]").click(function(){

var prescr=localStorage.getItem('prefScreen');

     if(prescr=='1'){
		$.mobile.changePage("index.html#search_pyxie",{ 
									  transition: "slide", 
									   reverse: true,
									  changeHash: false });							  
	}
	else if(prescr=='2'){
		 $.mobile.changePage("index.html#all_my_pyxies",{ 
								  transition: "slide", 
								   reverse: true,
								  changeHash: false });
	}
	else if(prescr=='3'){
	    $.mobile.changePage("index.html#home_page",{ 
								  transition: "slide", 
								   reverse: true,
								  changeHash: false });
	}
	else if(prescr=='4'){
	    $.mobile.changePage("index.html#add_pyxies",{ 
								  transition: "slide", 
								   reverse: true,
								  changeHash: false });
	}
	else{
	$.mobile.changePage("index.html#home_page",{ 
								  transition: "slide", 
								   reverse: true,
								  changeHash: false });
	}

});
//------------------------------------------------------creating pyxie------------------------------------
$("#create_pyxie_button").click(function(){
	   //put here
				   var nameOfPyxie=$("#name_of_pyxie").val();
				    var srchOfPyxie=$("#serchterm_of_pyxie").val();
				  
				   //var selected=$("input[type='checkbox'][name='imgCheck']:checked").length;
				   if(uploadPyxiePic==""){
				   alert("Please select an image for pyxie");
				   }				   
               else if(nameOfPyxie==""){
					 alert("Please Enter Pyxie Name");
					 event.preventDefault();
                  }
				else if(srchOfPyxie==""){
					 alert("Please Enter Valid Search Term");
					 event.preventDefault();
                  }
				 /* else if(selected<=1){
				  alert("Please select a source");
				  }*/
				  else{
				     showLoader();
						var favorite="";
					   var bool=false;
						$.each($("input[name='imgCheck']:checked"), function(){ 
							if(!bool){
							favorite+=$(this).val();
							bool=true;
							}
							else{
							favorite+=","+$(this).val();
							}
							//favorite.push($(this).val());
						});
						
							var formData=new FormData();
							formData.append('userid',$.trim($.session.get("globalUserID")));
							formData.append('pyxiename',nameOfPyxie);
							formData.append('location',localStorage.getItem('country_code'));
							formData.append('search_item',srchOfPyxie);
							formData.append('interest',favorite);
							formData.append('pyxieImage',uploadPyxiePic);
							console.log(formData);
						$.ajax({
						   url:path+"pyxies/pyxieservice/rest/pyxie/savepyxie",
						   type: 'POST',
			               data: formData,
			               processData: false,
			                contentType: false,
							  success: function(responseData, textStatus, jqXHR) 
							  {
							   console.log(responseData);
							   favorite.length = 0;
							   var newUser=jQuery.parseJSON(responseData);
							    console.log(newUser);
							 hideLoader();
							   executePyxieInfo(newUser);					   
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							   hideLoader();
								alert("Please try again after sometime!");
							  }
							});
					}	
				  
                  });
		  
//---------------------------Details Of Pyxie -------------------------------------------------		  
	function executePyxieInfo(responseData){
	showOutLoader();
				 $.each(responseData, function(idx, obj) {
				        
						if(idx==0){						
								particularPyxieId=obj.pyxieId;
								pyxieString=obj.searchItem;
								var pyxnm=obj.title;
								$("#update_name_pyxie").val(pyxnm);
								$("#update_st_of_pyxie").val(pyxieString);
								$("#pyxieViewName1").text(obj.title);
								$("#pyxieViewName2").text(obj.title);
								$("#pyxieViewName3").text(obj.title);
								$("#pyxieViewName4").text(obj.title);
								$("#pyxieViewName5").text(obj.title);
								$("#pyxieViewName6").text(obj.title);
								$("#pyxieViewName7").text(obj.title);                   
								$("#pyxieViewImage1").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage2").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage3").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage4").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage5").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage6").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");
								$("#pyxieViewImage7").css('background-image', "url(data:image/png;base64,"+ obj.pyxieImage+")");						
						}
								
				        });
				       hideOutLoader();
						  $.mobile.changePage("index.html#open_pyxie",{ 
						  transition: "fade", 
						  changeHash: false 
						  });
	}


$("#googleImagesTab").click(function(){
//put here
   getGoogleImages(); 
   pageNo="0";
});
$(document).on("pagebeforeshow","#open_pyxie",function(){
pageNo="0";
 $('#googleImagesTab').trigger('click');
 $('#appendGoogleImages').html("");
 
});

function getGoogleImages(){
     showLoader();
			   $.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/google_images?pyxieId="+particularPyxieId+"&page="+pageNo,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){
				   
				    $('#appendGoogleImages').html("");
				    var googleImages=jQuery.parseJSON(responseData);			  
                         var gimages="";									
						$.each(googleImages.result, function(idx, obj) {
							gimages+='<a href="'+obj.imageUrl+'" title="'+obj.description+'" style="margin:1px"><img src="'+obj.thumblineUrl+'" height="75px" width="100px"/></a>';	
						}); 
						
						$('#appendGoogleImages').html(gimages);
						getMoreGoogleImages();
						//$('#appendGoogleImages').append('<input type="button"  value="more" id="loadmoreImages" style="width:100%;height:25px;"/>');
						
                          // hideLoader();	                             	
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });
}

function getMoreGoogleImages(){
//put here
 showLoader();
 pageNo=parseInt(pageNo);
	 ++pageNo;
$.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/google_images?pyxieId="+particularPyxieId+"&page="+pageNo*8,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){				  
				   var googleImages=jQuery.parseJSON(responseData);			  
                         var gimages="";									
						$.each(googleImages.result, function(idx, obj) {
							gimages+='<a href="'+obj.imageUrl+'" title="'+obj.description+'" style="margin:1px"><img src="'+obj.thumblineUrl+'" height="75px" width="100px"/></a>';	
						});
						
						$('#appendGoogleImages').append(gimages);
                      $('#appendGoogleImages').append('<input type="button"  value="more" id="loadmoreImages"  style="width:98%;height:25px;"/>');
 
                           hideLoader();	                             	
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				    //alert("Error in Server Could not Update!!");
				  }		   
		   });

}
$(document).on('click', "#loadmoreImages", function() {
//put here
 $(this).remove();
 getMoreGoogleImages();
});
$("#flickrImagesTab").click(function(){
//put here
$('#appendFlickerImages').html(""); 
            showLoader();
			   $.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/flicker_images?pyxieId="+particularPyxieId,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){				   
				    $('#appendFlickerImages').html("");	
                      console.log(responseData);				
				   var flickImages=jQuery.parseJSON(responseData);				  
                        var fimages="";									
						 $.each(flickImages.result, function(idx, obj) {
								     fimages+='<a href="'+obj.imageUrl+'" title="'+obj.description+'" style="margin:1px"><img src="'+obj.thumblineUrl+'" height="75px" width="100px"/></a>';	
								   });
						$('#appendFlickerImages').html(fimages);	                 
                           hideLoader();		   
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				  alert("Please try again after sometime!");
				  }		   
		   });
});
		 
$("#pinterestImagesTab").click(function(){
pinPageNo="0";
 $('#appendPinterestImages').html("");
  showLoader();
  $.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/pintrest_images?pyxieId="+particularPyxieId+"&page="+pinPageNo,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){
				   
				    $('#appendPinterestImages').html("");
					
				      var PinterestImages=jQuery.parseJSON(responseData);	
                console.log(PinterestImages);			
                         var pimages="";									
						$.each(PinterestImages, function(idx, obj) {
							pimages+='<a href="'+obj.imageUrl+'" title="'+obj.description+'" style="margin:1px"><img src="'+obj.thumblineUrl+'" height="75px" width="100px"/></a>';	
						}); 
						$('#appendPinterestImages').html(pimages);
						getMorePinterestImages();						                             	
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });
	        
	 
 });
 function getMorePinterestImages(){
//put here
 showLoader();
 pinPageNo=parseInt(pinPageNo);
	 ++pinPageNo;
$.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/pintrest_images?pyxieId="+particularPyxieId+"&page="+pinPageNo*8,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){				  
				   var PinterestImages=jQuery.parseJSON(responseData);
    console.log(PinterestImages);				   
                         var pimages="";									
						$.each(PinterestImages, function(idx, obj) {
							pimages+='<a href="'+obj.imageUrl+'" title="'+obj.description+'" style="margin:1px"><img src="'+obj.thumblineUrl+'" height="75px" width="100px"/></a>';	
						});
						
						$('#appendPinterestImages').append(pimages);
                      $('#appendPinterestImages').append('<input type="button"  value="more" id="loadPinterestImgs"  style="width:98%;height:25px;"/>');
 
                           hideLoader();	                             	
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				    //alert("Error in Server Could not Update!!");
				  }		   
		   });

}
$(document).on('click', "#loadPinterestImgs", function() {
//put here
 $(this).remove();
 getMorePinterestImages();
});
//---------------------------------videos of pyxies-------------------------------------------------
$(document).on("pagebeforeshow","#videos_of_pyxie",function(){
//put here
 $('#youtubeVideoTab').trigger('click');
  $('#displayYoutubeVideos').html("");
  $('#displayVimeoVideos').html("");
  
 });	 	  	
 $(document).on("pageshow","#videos_of_pyxie", function () {
 //put here
	 getYoutubeImages();
	 });

function getYoutubeImages(){
	           showLoader();
			   $.ajax({			   
				  url:path+"pyxies/pyxieservice/rest/pyxie/youtube_images?pyxieId="+particularPyxieId,
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){				   				   			
				   var youtubeVids=jQuery.parseJSON(responseData);				  
                       $('#displayYoutubeVideos').html("");					 
							var youtube="<table align='center'>";
								   $.each(youtubeVids, function(idx, obj) { 
                                                                           
								   if(idx%2==0){	// <a   >Video #1</a> 								 
									  youtube+='<tr><td><a  class="fancybox fancybox.iframe"  href='+getEmbedId(obj.video_id)+' ><img src="'+obj.thumb+'"/></a></td>';
									   }
									   else{	
									   youtube+='<td><a class="fancybox fancybox.iframe"  href='+getEmbedId(obj.video_id)+' ><img src="'+obj.thumb+'"/></a></td></tr>';
									   }		
								   });
								    youtube+="</table>";
									
								  $('#displayYoutubeVideos').html(youtube);
                          hideLoader();								  
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });
	 }
	 
	 function getEmbedId(vidId){
	//var url_new=;
	// var res = url_new.split("/");
	 return  "http://www.youtube.com/embed/"+$.trim(vidId)+"?autoplay=1&wmode=opaque&fs=1";
	 }
	 
	 function getVimeo(url){
	 
	 var url_new=$.trim(url);
	var res = url_new.split("/");
   // http://player.vimeo.com/video/125591297?title=0&amp;byline=0&amp;portrait=0&amp;color=f2f2ea
	 return  "http://player.vimeo.com/video/"+$.trim(res[2])+"?title=0&autoplay=1";
	 }
	 
	

$(document).on("pageinit","#videos_of_pyxie", function () {

$("#youtubeVideoTab").click(function(){
//put here	
getYoutubeImages();
});
$("#vimeoVideoTab").click(function(){
//put here
	  showLoader();
			   $.ajax({			   
				  url:"https://api.vimeo.com/videos?access_token=efc475d8afd4d0c1f5c3dfce648fbf12&per_page=20&query="+$.trim(pyxieString)+"&sort=relevant&direction=desc", 
				  type: 'GET',
				   async:true,
				   dataType: 'json',	
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){				   				   			
				 		
								  $('#displayVimeoVideos').html("");	
								  var res=responseData.data;
								  var vimeo="<table align='center'>";
								   $.each(res, function(idx, obj) {
								   var url="";
								   var pic="";
									  console.log(idx+" "+obj.uri);
									  
									  var url=obj.uri;
										  $.each(obj.pictures.sizes, function(idx, obj1) {
												  if(idx==2)
												  {
												  pic=$.trim(obj1.link);
													console.log(obj1.link);
													return false;
												  }
										  });
										  
									if(idx%2==0){							 
									    vimeo+='<tr><td><a  class="fancybox fancybox.iframe"  href='+getVimeo(url)+' ><img src="'+pic+'" width="140px" height="100px"/></a></td>';
									   }
									   else{	
									   vimeo+='<td><a class="fancybox fancybox.iframe"  href='+getVimeo(url)+' ><img src="'+pic+'" width="140px" height="100px"/></a></td></tr>';
									   }
									   
							         });
									  vimeo+="</table>";
							   $('#displayVimeoVideos').html(vimeo);
                          hideLoader();								  
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });
	});
	
	/*$(document).on('vclick', '#displayVimeoVideos tr td a', function(){ //opening the vimeo video				
					var url=$.trim($(this).attr('data-id'));				       
	                 alert(url);
              });*/
	
});

//---------------------------------------------------socail of pyxie------------------------------------
$(document).on("pagebeforeshow","#social_of_pyxie",function(){
fbPageNo="0";
showLoader();
 $('#facebookSocialTab').trigger('click');
  $('#tweets').empty();
  $('#googlePlusPosts').empty();  
 });
$(document).on("pageinit","#social_of_pyxie", function () {
$('#appendInstagramImages').html("");

$("#twitterSocialTab").click(function(){
//put here
//alert($.trim(pyxieString));
		   var name="";
           var newname="";	
			name=$.trim(pyxieString).split(' ');
			for(i=0;i<name.length;i++){
				newname+=name[i];
			}
			showLoader();        			 
			   $.ajax({
				  url:path+'pyxies/pyxieservice/rest/pyxie/tweets?keyword='+$.trim(newname),
				  type: 'GET',
				   crossDomain: true,
				   success: function(responseData, textStatus, jqXHR){
				    $('#tweets').empty();  //List
					
						var tweetObj=jQuery.parseJSON(responseData);
                            console.log(tweetObj.length);						
                          if(tweetObj.length==0){
						  $('#tweets').append('<div align="center"><table><tr><td><p style="font-style:normal;color:#000000;">No data found</p></td></tr></table></div>');
						  }
						  else{
						  $.each(tweetObj, function(idx, obj) {
								  $('#tweets').append('<div style="border-bottom:solid 1px black;"><table><tr><td width="45"><img style="margin:4px;" align="top-left" height="45px" width="45px" src=\"'+obj.profile_image+'\"/></td><td><span style="font-weight:bold;color:#000000;">'+obj.user_name+'</span></td></tr><tr><td width="45"></td><td ><a href="" id="tweetOpen" data-id="'+getTwitterUrl(obj.tweet_desc)+'" style="text-decoration:none"><span style="font-weight:normal;color:#000;">'+obj.tweet_desc+'</span></a></td></tr></table></div>');
                                   
								  //$('#tweets').append('<div style="border-bottom:solid 1px black;"><table><tr><td><img style="margin:4px;" align="top-left" height="45px" width="45px" src=\"'+obj.profile_image+'\"/></td><td><p style="font-weight:bold;color:#000000;">'+obj.user_name+'</p></td></tr></table></div>');
                                     });
					               	
						  }
                             $('#tweets').listview().listview('refresh');					   
							 hideLoader();				
					},
				  error: function (responseData, textStatus, errorThrown) 
				  {
				  hideLoader();
				   alert("Please try again after sometime!");
				  }		   
		   });
   });
   
   function getTwitterUrl(data){
   var punctuation = ['!',"'",'"',',','.'];
var urllink="";
    var asasd=$.trim(data);
        $words = asasd.split(' ');
       for (i in $words){
                    if ($words[i].indexOf('http://') == 0||$words[i].indexOf('https://') == 0){
                //$words[i] = '<a href="' + $words[i] + '">' + $words[i] + '</a>';
                urllink=$words[i];
            }
        }
		//alert(urllink);
	   return urllink;   
   }
   
   $(document).on('vclick', 'a[id=tweetOpen]', function(event){
		  
		   var url=$.trim($(this).attr('data-id'));
         if(url!==""){		
		 window.open(url,"","");
		 }
   });
 
$("#facebookSocialTab").click(function(){
	 $('#facebookPosts').empty(); 
	 fbPageNo="0";
			showLoader();
			   $.ajax({
				  url:path+'pyxies/pyxieservice/rest/pyxie/fb_posts?pyxieId='+particularPyxieId+'&page='+fbPageNo,
				  type: 'GET',				
				   crossDomain: true,
					success: function(responseData, textStatus, jqXHR){
							      $('#facebookPosts').empty(); //List
									var fbPostsObj=jQuery.parseJSON(responseData);                          
									  
										 $.each(fbPostsObj.responseData.results, function(idx, obj) {
										 
											   $('#facebookPosts').append('<div style="border-bottom:solid 1px black;"><table><tr><td><span style="font-weight:bold;">'+obj.titleNoFormatting+'</span></td></tr><tr><td><a href="" id="fbOpen" data-id="'+obj.unescapedUrl+'" style="text-decoration:none"><span style="font-weight:normal!important;color:#000!important;">'+obj.content+'</span></a></td></tr></table></div>');
												 });
											   
												$('#facebookPosts').append('<input type="button"  value="more" id="loadMoreFb"  style="width:98%;height:25px;"/>');
											   $('#facebookPosts').listview().listview('refresh');						   
										
										hideLoader();			
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!!");
							  }		   
					   });
	});
	
   $(document).on('click', "#loadMoreFb", function() {
//put here
 $(this).remove();

 fbPageNo=parseInt(fbPageNo);
	 ++fbPageNo;
    showLoader();
			   $.ajax({
				  url:path+'pyxies/pyxieservice/rest/pyxie/fb_posts?pyxieId='+particularPyxieId+'&page='+fbPageNo*8,
				  type: 'GET',				
				   crossDomain: true,
					success: function(responseData, textStatus, jqXHR){
							     //List
									var fbPostsObj=jQuery.parseJSON(responseData);                          
									  
										 $.each(fbPostsObj.responseData.results, function(idx, obj) {
										 
											   $('#facebookPosts').append('<div style="border-bottom:solid 1px black;"><table><tr><td><span style="font-weight:bold;">'+obj.titleNoFormatting+'</span></td></tr><tr><td><a href="" id="fbOpen" data-id="'+obj.unescapedUrl+'" style="text-decoration:none"><span style="font-weight:normal!important;color:#000!important;">'+obj.content+'</span></a></td></tr></table></div>');
												 });
											   
												$('#facebookPosts').append('<input type="button"  value="more" id="loadMoreFb"  style="width:98%;height:25px;"/>');
											   $('#facebookPosts').listview().listview('refresh');						   
										
										hideLoader();			
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!!");
							  }		   
					   });
});

$(document).on('vclick', 'a[id=fbOpen]', function(event){		  
		   var url=$.trim($(this).attr('data-id'));
         if(url!==""){		
		 window.open(url,"","");
		 }
   });
   
$("#gplusSocialTab").click(function(){

if(window.navigator.onLine){
    $('#googlePlusPosts').html("");
    getGoogleplusData();
	}
	else{
	alert("Please check your internet connection");
	}
    
  
			
	});
	
function getGoogleplusData()
	{
	//https://www.googleapis.com/plus/v1/activities?query='+$.trim(pyxieString)+'&maxResults=20&orderBy=best&key=AIzaSyAFC8mbF1LW0HMzaba5ohCht38xOG_CWZE
	  // showLoader(); 
	  //alert(path+'pyxies/pyxieservice/rest/pyxie/google?keyword='+$.trim(pyxieString));
			$.ajax({
				url:path+'pyxies/pyxieservice/rest/pyxie/google?keyword='+$.trim(pyxieString),
				type: 'GET',
                async:true,
				dataType : 'json',				
				crossDomain: true,
				success: function(responseData, textStatus, jqXHR){
				  $('#googlePlusPosts').html("");
				        console.log(responseData.items);
						if(responseData.items==""){
						   getGoogleplusData();
						}
						else{
						 $.each(responseData.items, function(idx, obj1) {
						
						 $.each(obj1.object.attachments, function(idx, obj) {	
									//$('#googlePlusPosts').append('<div style="border-bottom:solid 1px black;"><table><tr><td><img style="margin:4px;" align="top-left" height="45px" width="45px" src=\"'++'\"/></td><td><p style="font-weight:bold;;color:#000000;">'++'</p><a href="" id="gplus_n" data-id="'++'" style="text-decoration:none;"><p style="font-weight:lighter!important;font-style:normal;color:#000;">'++'</p></a></td></tr></table></div>');
									$('#googlePlusPosts').append('<div style="border-bottom:solid 1px black;"><table><tr><td width="45"><img style="margin:4px;" align="top-left" height="45px" width="45px" src=\"'+obj1.actor.image.url+'\"/></td><td><span style="font-weight:bold;color:#000000;">'+obj1.actor.displayName+'</span></td></tr><tr><td colspan="2"><a href="" id="gplus_n" data-id="'+obj.url+'" style="text-decoration:none"><span style="font-weight:normal;color:#000;">'+obj.displayName+'</span></a></td></tr></table></div>');
									});	
							});
					    $('#googlePlusPosts').listview().listview('refresh');
						}	
				},
				error: function (responseData, textStatus, errorThrown) 
				{
					alert("Please try again after sometime!");
				}		   
			});
 }
 
 $(document).on('vclick', 'a[id=gplus_n]', function(event){
		
		   var url=$.trim($(this).attr('data-id'));
         if(url!==""){
		
		 window.open(url,"","");

		 }

 });
		  
$("#instagramSocialTab").click(function(){
//put here
$('#appendInstagramImages').html("");
 showLoader();
    var name="";
    var newname="";	
	name=$.trim(pyxieString).split(' ');
    for(i=0;i<name.length;i++){
        newname+=name[i];
    }
	
	$('.instagram').on('didLoadInstagram', function(event, response) {
				
      console.log(response.data);
	  
	  if(response.data==""){
	   $('#appendInstagramImages').html("No Images found with #"+$.trim(newname));
	   hideLoader();
	  }
	  else{
	  $('#appendInstagramImages').html("");
				    	var instaimages="";							
						$.each(response.data, function(idx, obj) { 
						var str="Posted By :"+obj.caption.from.username+"</br>"+"Caption :"+obj.caption.text;
							instaimages+='<a href="'+obj.images.standard_resolution.url+'" title="'+str+'" style="margin:1px"><img src="'+obj.images.thumbnail.url+'" height="75px" width="100px"/></a>';	
						}); 
						$('#appendInstagramImages').html(instaimages);
						hideLoader();
	  }
	   
	  
	  });  
		   $('.instagram').instagram({
			hash: $.trim(newname),
			count: '30',
			clientId: '029bb5a5a3274859ae046385fbbf01af'
		  });
	});
	
	
});//social page init
//--------------------------------------------------new of pyxie--------------------------------------------
$(document).on("pagebeforeshow","#news_of_pyxie",function(){
//put here
 $('#timeNewsTab').trigger('click');
 $('#TimeNewsList').empty(); 
  $('#GoogleNewsList').empty();     
  $('#BBCNewsList').empty(); 
  $('#CNNNewsList').empty();
 });
  $(document).on("pageshow","#news_of_pyxie", function () {
  //put here
	 getTimesNews();
	 });
	 function  getTimesNews(){
	  $('#TimeNewsList').empty();
	 showLoader();
			   $.ajax({
				  url:path+'pyxies/pyxieservice/rest/pyxie/feeds?type=times&keyword='+$.trim(pyxieString),
				  type: 'GET',
				   crossDomain: true,
					success: function(responseData, textStatus, jqXHR){
							    $('#TimeNewsList').empty();  //List
									var timeNews=jQuery.parseJSON(responseData);                          
									 
									   if(timeNews==""){
									      $('#TimeNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');
										  // $('#TimeNewsList').append('<div align="center"><table><tr><td><a href="" id="openTime"  style="text-decoration:none;"><p style="font-style:normal;color:#000000;">Search here!!</p></a></td></tr></table></div>');
											$('#TimeNewsList').listview().listview('refresh');
									   }
									   else{
									   
											   if(timeNews.responseData.entries.length==0){
											   $('#TimeNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');
											   }
											   else{
											   $.each(timeNews.responseData.entries, function(idx, obj) {
													   //$('#TimeNewsList').append('<table style="border-bottom:solid 1px black"><tr><td><a href="" id="timen" data-id="'+obj.link+'" style="text-decoration:none;"><p style="font-style:normal;color:#000000;">'+obj.title+'</p></a></td></tr><tr><td><p style="font-style:normal;color:#000000;">'+obj.contentSnippet+'</p></td></tr></table>');
													$('#TimeNewsList').append('<div style="border-bottom:solid 1px black;padding:1px;"><div><a href="" id="timen" data-id="'+obj.link+'" style="text-decoration:none;"><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.title+'</p></a></div><div><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.contentSnippet+'</p></div></div>');
													});
											   }
											   $('#TimeNewsList').listview().listview('refresh');	
									   } 
                                        hideLoader();									   
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!");
							  }		   
					   });
					   
	 }
	 
	 $(document).on('vclick', 'a[id=timen]', function(event){
    var url=$.trim($(this).attr('data-id'));
    if(url!=""){
    window.open(url,"","");
    }  
    event.stopPropagation();
  });
   $(document).on('vclick', 'a[id=openTime]', function(event){
		
		 window.open("http://search.time.com/results.html?Ntt="+$.trim(pyxieString),"","");

 });
  
$(document).on("pageinit","#news_of_pyxie", function () {
     
$("#timeNewsTab").click(function(){
//put here
	getTimesNews();			
	});
	
	$("#cnnNewsTab").click(function(){
	//put here 
	 $('#CNNNewsList').empty(); 
			showLoader();

					   $.ajax({
						  url:path+'pyxies/pyxieservice/rest/pyxie/feeds?type=cnn&keyword='+$.trim(pyxieString),
						  type: 'GET',
				          crossDomain: true,
							   success: function(responseData, textStatus, jqXHR){
							    $('#CNNNewsList').empty();    //List
									var cnnNewsListObj=jQuery.parseJSON(responseData);                          
									 console.log(cnnNewsListObj);
									   if(cnnNewsListObj==""){
											$('#CNNNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');
										    //$('#CNNNewsList').append('<div align="center"><table><tr><td><a href="" id="openCnn"  style="text-decoration:none;"><p style="font-style:normal;color:#000000;">Search here!!</p></a></td></tr></table></div>');		   
											$('#CNNNewsList').listview().listview('refresh');	
									   }
									   else{
											if(cnnNewsListObj.responseData.entries.length==0){
											$('#CNNNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');							
											}
											else{
											$.each(cnnNewsListObj.responseData.entries, function(idx, obj) {
														   $('#CNNNewsList').append('<div style="border-bottom:solid 1px black;padding:1px;"><div><a href="" id="timen" data-id="'+obj.link+'" style="text-decoration:none;"><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.title+'</p></a></div><div><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.contentSnippet+'</p></div></div>');
															 });
											}
											$('#CNNNewsList').listview().listview('refresh');	   
									}
				                    hideLoader();
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!");
							  }		   
					   });
	});
	
	$(document).on('vclick', 'a[id=cnn_n]', function(){
   var url=$.trim($(this).attr('data-id'));
	 if(url!=""){
	  window.open(url,"","");
	 }
  
  });
  
  $(document).on('vclick', 'a[id=openCnn]', function(event){	
//http://edition.cnn.com/SEARCH/?text=flowers
		 window.open("http://edition.cnn.com/search/?text="+$.trim(pyxieString),"","");
 });
  
	$("#bbcNewsTab").click(function(){
	 $('#BBCNewsList').empty(); 
	 //put here
			       showLoader();
					   $.ajax({
						  url:path+'pyxies/pyxieservice/rest/pyxie/feeds?type=bbc&keyword='+$.trim(pyxieString),
						  type: 'GET',
						   crossDomain: true,
							   success: function(responseData, textStatus, jqXHR){
							   $('#BBCNewsList').empty();     //List  $('#CNNNewsList').empty();
									var bbcnewsListObj=jQuery.parseJSON(responseData);                          
									   
                                         if(bbcnewsListObj==""){
											$('#BBCNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information found on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');
											//$('#BBCNewsList').append('<div align="center"><table><tr><td><a href="" id="openBbc"  style="text-decoration:none;"><p style="font-style:normal;color:#000000;">Search here!!</p></a></td></tr></table></div>');		   
											$('#BBCNewsList').listview().listview('refresh');	
									   }
                                      else{
												if(bbcnewsListObj.responseData.entries.length==0){
												$('#BBCNewsList').append('<div style="border-bottom:solid 1px black;"><table><tr><td><p style="font-style:normal;color:#000000;">No information found on '+$.trim(pyxieString)+' at the moment</p></td></tr></table></div>');
												}
												else{												
													$.each(bbcnewsListObj.responseData.entries, function(idx, obj) {
												       $('#BBCNewsList').append('<div style="border-bottom:solid 1px black;padding:1px;"><div><a href="" id="timen" data-id="'+obj.link+'" style="text-decoration:none;"><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.title+'</p></a></div><div><p style="font-style:normal;color:#000000;padding-left:3px;">'+obj.contentSnippet+'</p></div></div>');
													 });
												 
												}
											   $('#BBCNewsList').listview().listview('refresh');
									 }
                                hideLoader();									 
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!");
							  }		   
					   });
	});
	
	$(document).on('vclick', 'a[id=bbc_n]', function(){
   var url=$.trim($(this).attr('data-id'));
	   if(url!=""){
		window.open(url,"","");
	   } 
  });
  
  $(document).on('vclick', 'a[id=openBbc]', function(event){		
		 window.open("http://www.bbc.co.uk/search?q="+$.trim(pyxieString),"","");
 });
  
	$("#googleNewsTab").click(function(){
	//put here
	  showLoader();
					   $.ajax({
						  url:path+"pyxies/pyxieservice/rest/pyxie/google_news?searchItem="+$.trim(pyxieString),
						  type: 'GET',
						   crossDomain: true,
							   success: function(responseData, textStatus, jqXHR){
							   $('#GoogleNewsList').empty();     //List 
									var googleNews=jQuery.parseJSON(responseData);                          
									   hideLoader();	
										 $.each(googleNews.result, function(idx, obj) {
											   $('#GoogleNewsList').append('<table style="border-bottom:solid 1px black"><tr><td><a href="" id="gog_n" data-id="'+obj.originalContextUrl+'" style="text-decoration:none"><p style="font-style:normal;color:#000000;">'+obj.title+'</p></a></td><td><img style="margin:5px;" height="45px" width="45px" src=\"'+obj.thumblineUrl+'\"/></td></tr><tr><td><p style="font-style:normal;color:#000000;">'+obj.description+'</p></td></tr></table>');
												 });
											   $('#GoogleNewsList').listview().listview('refresh');						   
													
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!");
							  }		   
					   });
	     });

		 $(document).on('vclick', 'a[id=gog_n]', function(){
		   //alert($.trim($(this).attr('data-id')));
		   var url=$.trim($(this).attr('data-id'));

		   //cordova.InAppBrowser.open(url, '_blank', 'location=yes');
		  window.open(url,"","");
		  });		 
});
//------------------------------------------------more options----------------------------------------------------


$(document).on("pagebeforeshow","#more_options",function(){
 $('#imdbTab').trigger('click');
   $('#ImdbList').empty(); 
 });


function getImdbDetails(){
$('#ImdbList').empty();
                       showLoader();
					   $.ajax({
						  url:"http://www.imdbapi.com/?s="+$.trim(pyxieString),
						  type: 'GET',
						   crossDomain: true,
							   success: function(responseData, textStatus, jqXHR){
							           $('#ImdbList').empty();  
									//var imdb=jQuery.parseJSON(responseData);
                            			console.log(responseData);						
									    //alert(imdb);
									    if(responseData.Error=="Movie not found!")
											 {
											 $('#ImdbList').append('<div align="center"><table><tr><td><p style="font-style:normal;color:#000000;">No data found</p></td></tr></table></div>');
											 
											 }
											 else{											 
											 $.each(responseData.Search, function(idx, obj) {
											
											   $('#ImdbList').append('<li style="border-bottom:solid 1px black"><a href="" id="imdbTable" data-id='+obj.imdbID+'><p  style="font-size:13px!important;font-weight:bold!important;" >'+obj.Title+'</p><p>'+obj.Year+'</p><p>'+obj.Type+'</p></a></li>');											 
										       });
										
											 }
										$('#ImdbList').listview().listview('refresh');					   
										  hideLoader();	  			
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							  hideLoader();
								alert("Please try again after sometime!");
							  }		   
					   });			
    }

$(document).on('vclick', 'a[id=imdbTable]', function(){
		   //alert($.trim($(this).attr('data-id')));
		   var id=$.trim($(this).attr('data-id'));
		  // alert(id);
                    var url="http://www.imdb.com/title/"+id+"/?ref_=nv_sr_1";
					//alert(url);
					//cordova.InAppBrowser.open('http://www.imdb.com/title/tt1628033/?ref_=nv_sr_1', '_system', 'location=yes');
		   //cordova.InAppBrowser.open(url, '_system', 'location=yes');
		   window.open(url,"","");
		  
		  });

$(document).on("pageinit","#more_options", function () {
     $('#bingresults').empty();
	  $('#wikiresults').empty(); 
		$("#imdbTab").click(function(){
		//put here
		getImdbDetails();
		});
		
		$("#bingTab").click(function(){
		//put here
		 $('#bingresults').empty(); 
		 bingPgno=1;
		doSearch(bingPgno);
		});
		
		$("#wikipediaTab").click(function(){
		//put here
		     showLoader();
			  $('#wikiresults').empty(); 
		       $.ajax({
						  url:"http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search="+$.trim(pyxieString)+"&suggest=&format=json",
						  type: 'GET',
						  async:true,
				           dataType: 'jsonp',
						   crossDomain: true,
							   success: function(responseData, textStatus, jqXHR){
							        $('#wikiresults').empty();  
									var labels=[];
		                            var data=[];
									if(responseData[1].length==0){									
									$('#wikiresults').append('<table align="center" ><tr><p align="center" style="font-size:13px!important;">Data Not Found.Please check your Pyxie-Search Term</p></tr></table>');									  
									}
									else{
									 $.each(responseData[1], function(idx, obj) {
									   labels[idx]=obj;									 									
									   });
									   $.each(responseData[2], function(idx, obj) {
									   data[idx]=obj;																		
									   });									
									  $.each(responseData[3], function(idx, obj) {
									  $('#wikiresults').append('<div style="margin:1px!important;border-bottom:solid 1px black;"><table><tr><td><span style="font-weight:bold;color:#000;">'+labels[idx]+'</span></td></tr><tr><td><span style="font-weight:lighter;color:#000;">'+data[idx]+'</span></td></tr><tr><td><a href="" id="wiki_n" data-id="'+$.trim(obj)+'" ><span style="font-weight:lighter!important;font-style:normal;color:#000;">'+$.trim(obj)+'</span></a></td></tr></table></div>');
									   //$('#wikiresults').append('<div style="margin:4px!important;border-bottom:solid 1px black;"><div><p style="font-weight:bold;color:#000;">'++'</p></div><div><p style="font-weight:lighter;color:#000;">'++'</p></div><div><a href="" id="wiki_n" data-id="'+$.trim(obj)+'" ><p style="font-weight:lighter!important;font-style:normal;color:#000;">'++'</p></a></div></div>');									  
									   });
									}
									   
									   $('#wikiresults').listview().listview('refresh');
										hideLoader();					   
													
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							     hideLoader();
								alert("Please try again after sometime!");
							 }		   
					   });
		});
		
		$("#amazonTab").click(function(){
		//put here
		     showLoader();
			  $('#amazonresults').empty(); 
			  invokeRequest();
			  //alert(mainurl);
			  var formData=new FormData();
			  formData.append('url',$.trim(mainurl));	
		             $.ajax({
						   url:path+"pyxies/pyxieservice/rest/pyxie/amazon",
						   type: 'POST',						
						    data: formData,
							processData: false,
							contentType: false,
							   success: function(responseData, textStatus, jqXHR){
							   setTimeout(function(){
										 hideLoader();
										}, 10000);
							        $('#amazonresults').empty();  
									
									var amazonres=jQuery.parseJSON(responseData);                          
                          	console.log(amazonres);
                             $.each(amazonres.ItemSearchResponse.Items.Item, function(idx, obj) {
							//<td><p style="font-weight:bold;color:#000000;">'+obj.user_name+'</p><a href="" id="tweetOpen" data-id="'+getTwitterUrl(obj.tweet_desc)+'" style="text-decoration:none"><p style="font-style:normal;color:#000000;">'+obj.tweet_desc+'</p></a></td>
								   $('#amazonresults').append('<div style="border-bottom:solid 1px black;"><table><tr><td><img style="margin:4px;" align="top-left" height="45px" width="45px" src=\"'+obj.MediumImage.URL+'\"/></td><td><a href="" id="amazonOpen" data-id="'+obj.DetailPageURL+'" style="text-decoration:none"><p style="font-weight:normal;color:#000000;">'+obj.ItemAttributes.Title+'</p></a></tr></table></div>');
                                     });
					               $('#amazonresults').listview().listview('refresh');	
								   
										hideLoader();	
                                        
				
								},
							  error: function (responseData, textStatus, errorThrown) 
							  {
							     hideLoader();
								alert("Please try again after sometime!");
							 }		   
					   });
		});
		
		$(document).on('vclick', 'a[id=amazonOpen]', function(){
		
			   var url=$.trim($(this).attr('data-id'));
			 if(url!=""){
			  window.open(url,"","");
			 }

		  });
		
		function invokeRequest() {

        var unsignedUrl ="http://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAJOZU4ENAAXOULQHA&AssociateTag=PYXIES-21&Condition=All&Keywords="+$.trim(pyxieString)+"&Operation=ItemSearch&ResponseGroup=Images%2CItemAttributes&SearchIndex=All&Service=AWSECommerceService&Version=2011-08-01";
	var lines = unsignedUrl.split("\n");
	unsignedUrl = "";
	for (var i in lines) { unsignedUrl += lines[i]; }

        var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
        var matches = urlregex.exec(unsignedUrl);

	if (matches == null) {
	  alert("Could not find PA-API end-point in the URL. Please ensure the URL looks like the example provided.");
	  return;
	}

        var host = matches[1].toLowerCase();
        var query = matches[2];

        var pairs = query.split("&");

        pairs = cleanupRequest(pairs);

        pairs = encodeNameValuePairs(pairs);

        pairs.sort();
        var canonicalQuery = pairs.join("&");
        var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;

        var secret = "3/SC2zP41IhSkF8kL1Hmq2pKKdAn6RFsYul3+TuP";
        var signature = sign(secret, stringToSign);

        var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;

		mainurl= signedUrl;
      }
	  function encodeNameValuePairs(pairs) {
        for (var i = 0; i < pairs.length; i++) {
          var name = "";
          var value = "";
          
          var pair = pairs[i];
          var index = pair.indexOf("=");

          // take care of special cases like "&foo&", "&foo=&" and "&=foo&" 
          if (index == -1) {
            name = pair;
          } else if (index == 0) {
            value = pair;
          } else {
            name = pair.substring(0, index);
            if (index < pair.length - 1) {
              value = pair.substring(index + 1);
            }
          }
          
	  // decode and encode to make sure we undo any incorrect encoding
          name = encodeURIComponent(decodeURIComponent(name));

	  value = value.replace(/\+/g, "%20");
          value = encodeURIComponent(decodeURIComponent(value));

          pairs[i] = name + "=" + value;
        }

        return pairs;
      }
	  
	  function cleanupRequest(pairs) {
        var haveTimestamp = false;
	var haveAwsId = false;
        var accessKeyId ="AKIAJOZU4ENAAXOULQHA";
        
        var nPairs = pairs.length;
        var i = 0;
        while (i < nPairs) {
          var p = pairs[i];
          if (p.search(/^Timestamp=/) != -1) {
            haveTimestamp = true;
          } else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
            pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
	    haveAwsId = true;
          } else if (p.search(/^Signature=/) != -1) {
            pairs.splice(i, 1);
            i--;
            nPairs--;
          }
          i++;
        }

        if (!haveTimestamp) {
          pairs.push("Timestamp=" + getNowTimeStamp());
        }

	if (!haveAwsId) {
	  pairs.push("AWSAccessKeyId=" + accessKeyId);
	}
        return pairs;
      }
	  
	  function sign(secret, message) {
        var messageBytes = str2binb(message);
        var secretBytes = str2binb(secret);
        
        if (secretBytes.length > 16) {
            secretBytes = core_sha256(secretBytes, secret.length * chrsz);
        }
        
        var ipad = Array(16), opad = Array(16);
        for (var i = 0; i < 16; i++) { 
            ipad[i] = secretBytes[i] ^ 0x36363636;
            opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
        }

        var imsg = ipad.concat(messageBytes);
        var ihash = core_sha256(imsg, 512 + message.length * chrsz);
        var omsg = opad.concat(ihash);
        var ohash = core_sha256(omsg, 512 + 256);
        
        var b64hash = binb2b64(ohash);
        var urlhash = encodeURIComponent(b64hash);
        
        return urlhash;
      }
	  function getNowTimeStamp() {
	  var currentdate = new Date();
	  return currentdate.toISOString();
	 
      }
		
		$(document).on('vclick', 'a[id=wiki_n]', function(){
		    var url=$.trim($(this).attr('data-id'));			
		  // cordova.InAppBrowser.open(url, '_blank', 'location=yes');	 
       window.open(url,"","");		  
		  });
	
    $(document).on('vclick', '#bingresults input[id=loadmorebing]', function(){	   
				$(this).remove();
					   ++bingPgno;
					  //put here
					   doSearch(bingPgno);
					 
	});
	function doSearch(Pgno) {
              showLoader();
				$.bingSearch({
					appKey: "6b82vu0IOtj9boh5gZ+VX+NwghLY2hTBQwjXpO0LQ7M",
					pageNumber: Pgno,
					query: $.trim(pyxieString),
					debug: false,
					beforeSearchResults: function(data) {
					},
					searchResultIterator: function(data) {	
					$('#bingresults').append('<div style="margin:1px!important;border-bottom:solid 1px black;"><table><tr><td><span style="font-weight:bold;color:#000;">'+data.Title+'</span></td></tr><tr><td><span style="font-weight:lighter;color:#000;">'+data.Description+'</span></td></tr><tr><td><a href="" id="bing_n" data-id="'+data.Url+'" ><span style="font-weight:lighter!important;font-style:normal;color:#000;">'+data.DisplayUrl+'</span></a></td></tr></table></div>');
						
					},
					afterSearchResults: function(data) {
					$('#bingresults').append('<input type="button"  value="more" id="loadmorebing"  style="width:98%;height:25px;"/>');
					
					$('#bingresults').listview().listview('refresh');	
                 hideLoader();
					}
				});	
  }
         $(document).on('vclick', 'a[id=bing_n]', function(){
		 
		   var url=$.trim($(this).attr('data-id'));

		  window.open(url,"","");
		  });
		
});			  
function scale(width, height, padding, border) {
        var scrWidth = $(window).width() - 10,
        scrHeight = $(window).height() - 10,
        ifrPadding = 1 * padding,
        ifrBorder = 2 * border,
        ifrWidth = width + ifrPadding + ifrBorder,
        ifrHeight = height + ifrPadding + ifrBorder,
        h, w;

        if (ifrWidth < scrWidth && ifrHeight < scrHeight) {
            w = ifrWidth;
            h = ifrHeight;
        } else if ((ifrWidth / scrWidth) > (ifrHeight / scrHeight)) {
            w = scrWidth;
            h = (scrWidth / ifrWidth) * ifrHeight;
        } else {
            h = scrHeight;
            w = (scrHeight / ifrHeight) * ifrWidth;
        }

        return {
            'width': w - (ifrPadding + ifrBorder),
            'height': h - (ifrPadding + ifrBorder)
        };
    }		  
	
//-----------------------------------Saving a Pyxie --------------------------------------------------------


$(document).on("pageshow","#pyxie_settings",function(){
//put here
                  $.ajax({
						   url:path+"pyxies/pyxieservice/rest/pyxie/settingsInfo?pyxieId="+particularPyxieId,
						   type: 'GET',
			                crossDomain: true,
							  success: function(responseData, textStatus, jqXHR) 
							  {
							  
							  console.log(responseData);
							   var i;
							   var data=jQuery.parseJSON(responseData);
							   var mediaIds=data.mediaIds;
							     console.log(mediaIds);
							   var arr=mediaIds.split(",");
							     for(i=0;i<arr.length;i++){
										 if(arr[i]!=""){
										 switchCase(arr[i]); 
									       }
								      }
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							   hideLoader();
								alert("Please try again after sometime!");
							  }
							});
});


function switchCase(no){


		switch(no){
		        case "1":day = $('input[name=imgUpCheck][type=checkbox][id=googleCheck_up]').prop('checked', true); 
                      		$("#google_image_up").addClass("google_on");		
				break;
				case "2":day = $('input[name=imgUpCheck][type=checkbox][id=pinterestCheck_up]').prop('checked', true);
					        $("#pinterest_image_up").addClass("pinterest_on");
				break;
				case "3":day = $('input[name=imgUpCheck][type=checkbox][id=flickrCheck_up]').prop('checked', true);
				 	          $("#flickr_image_up").addClass("flickr_on");
				break;
				case "4":day = $('input[name=imgUpCheck][type=checkbox][id=youtubeCheck_up]').prop('checked', true);
					    $("#youtube_image_up").addClass("youtube_on"); 
				break;
				case "5":day = $('input[name=imgUpCheck][type=checkbox][id=vimeoCheck_up]').prop('checked', true);
				      $("#vimeo_image_up").addClass("vimeo_on");
				break;
				case "6":day = $('input[name=imgUpCheck][type=checkbox][id=facebookCheck_up]').prop('checked', true);
					$("#facebook_image_up").addClass("facebook_on");
				break;
				case "7":day = $('input[name=imgUpCheck][type=checkbox][id=twitter_social_Check_up]').prop('checked', true);
				 	$("#twitter_social_image_up").addClass("twitter_on");
				break;
				case "8":day = $('input[name=imgUpCheck][type=checkbox][id=google_plus_Check_up]').prop('checked', true);
				 $("#google_plus_image_up").addClass("google_plus_on");
				break;
				case "9":day = $('input[name=imgUpCheck][type=checkbox][id=instagram_Check_up]').prop('checked', true);
				 	$("#instagram_image_up").addClass("instagram_on");
				break;
				case "10":day = $('input[name=imgUpCheck][type=checkbox][id=timesCheck_up]').prop('checked', true);
				 	$("#times_image_up").addClass("times_on"); 
				break;
				case "11":day = $('input[name=imgUpCheck][type=checkbox][id=cnnCheck_up]').prop('checked', true);
					$("#cnn_image_up").addClass("cnn_on");
				break;
				case "12":day = $('input[name=imgUpCheck][type=checkbox][id=bbcCheck_up]').prop('checked', true);
				 	$("#bbc_image_up").addClass("bbc_on");
				break;
				case "13":day = $('input[name=imgUpCheck][type=checkbox][id=google_news_Check_up]').prop('checked', true);
					$("#google_news_image_up").addClass("google_news_on");
				break;
				case "14":day = $('input[name=imgUpCheck][type=checkbox][id=imdbCheck_up]').prop('checked', true);
					$("#imdb_image_up").addClass("imdb_on");
				break;
				case "15":day = $('input[name=imgUpCheck][type=checkbox][id=bingCheck_up]').prop('checked', true);
				 	$("#bing_image_up").addClass("bing_on"); 
				break;
				case "16":day = $('input[name=imgUpCheck][type=checkbox][id=wikipediaCheck_up]').prop('checked', true);
					$("#wikipedia_image_up").addClass("wikipedia_on"); 
				break;
				case "18":day = $('input[name=imgUpCheck][type=checkbox][id=feedzillaCheck_up]').prop('checked', true);
				$("#feedzilla_image_up").addClass("feedzilla_on");
				break;					
		}
}
//---------------------------------------------------uploading of images--------------------------------------------------------
$("#goToUploadPic").click(function(){
$("#upPic").css('display','none');
 $("#UserCroppedImage").css('display','block');
$.mobile.changePage("index.html#upload_pic",{ 
						  transition: "fade", 
						  changeHash: false 
						  });
});

$(document).on("pageinit","#cropUploadPic", function () {
$('.image-editor').cropit({
				  imageState: {
					src: ''
				  }
				});
				$('.export').click(function() {
				  var imageData = $('.image-editor').cropit('export');
				   $('#cropped').css('background-image', 'url('+imageData+')');	 
				  uploadNewUserPic=getBlob(imageData);				  
				
				});			
});
 //-----------------------------------------  
$("#goToProfileSettings").click(function(){

$("#updateProPic").css('display','none');
 $("#updateCroppedImage").css('display','block');
$.mobile.changePage("index.html#profile_settings",{ 
						  transition: "slide",
                           reverse: true,						  
						  changeHash: false 
						  });
});

$(document).on("pageinit","#updateProfilePic", function () {
$('.image-editor1').cropit({
				  imageState: {
					src: ''
				  }
				});
				$('.export1').click(function() {
				  var imageData = $('.image-editor1').cropit('export');
				   $('#cropped1').css('background-image', 'url('+imageData+')');	 
				  updateOldPic=getBlob(imageData);				  

				});			
});
 //----------------------------------------------------------------------   
$("#goToSelectSources").click(function(){

$("#uploadPyxieImage").css('display','none');
$("#uploadCropPyxieImage").css('display','block');
 
				  
$.mobile.changePage("index.html#select_sources",{ 
						 transition: "slide",
                           reverse: true,
						  changeHash: false 
						  });
});



$(document).on("pageinit","#uploadPyxiePicture", function () {
$('.image-editor2').cropit({
				  imageState: {
					src: ''
				  }
				});
				$('.export2').click(function() {
				  var imageData = $('.image-editor2').cropit('export');
				   $('#cropped2').css('background-image', 'url('+imageData+')');	 
				  uploadPyxiePic=getBlob(imageData);				  
				
				});			
});
//-----------------------------------------------------------
$("#gobackPyxieSettings").click(function(){

$.mobile.changePage("index.html#pyxie_settings",{ 
						 transition: "slide",
                           reverse: true,
						  changeHash: false 
						  });
});

$(document).on("pageinit","#updatePyxieImage", function () {
		$('.image-editor3').cropit({
						  imageState: {
							src: ''
						  }
						});
				$('.export3').click(function() {
				  var imageData = $('.image-editor3').cropit('export');
				   $('#pyxieViewImage7').css('background-image', 'url('+imageData+')');	 
				  updatePyxiePic=getBlob(imageData);				  
				
				});			
});

function getBlob(imageData)
 {
                    var b64 = imageData.replace('data:image/png;base64,','');
                    var binary = atob(b64);
                    var array = [];
                    for (var i = 0; i < binary.length; i++) {
                        array.push(binary.charCodeAt(i));
                    }
                    return  new Blob([new Uint8Array(array)], {type: 'image/png'});
  }
				
//--------------------------forgot password---------------------
$("#for_pass").click(function(){
$("#plsenter").val(""); 
$.mobile.changePage("index.html#forgot_password",{ 
					transition: "fade",
					changeHash: false 
					});
});
$("#submit").click(function(){
//put here

 if(window.navigator.onLine){
     var email=$("#plsenter").val();
			var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
            if(email.length<1){
				   alert("Email cannot be blank");
					event.preventDefault();
                 }
               else if(!regex.test(email)){
                  alert("Please Enter Valid Email");
               event.preventDefault();
                }
				else{
					showOutLoader();
					var formData=new FormData();
					 formData.append('email',$.trim(email));
					  $.ajax({
						url:path+"pyxies/userservice/forgotpassword",
						type: 'POST',
						data: formData,
						processData: false,
						contentType: false,
						success: function(responseData, textStatus, jqXHR) 
						{
								console.log(responseData);
								 var emailstat=jQuery.parseJSON(responseData);
							if(emailstat.status=="success"){
							 alert(emailstat.message);
							 $.mobile.changePage("index.html#email_sign_in",{ 
												 transition: "fade",
												  changeHash: false 
												  });
							}
							else if(emailstat.status=="failure"){
						       alert(emailstat.message);
							}
							hideLoader();
								
					   
						},
						error: function (responseData, textStatus, errorThrown) 
						{
										hideLoader();
										alert("Please try again after sometime!");
						}
					});
				}
	}
	else{
	alert("Please check your internet connection");
	}

			
  });
  //---------------------------------------------------change profile password-----------------
  $("#chsubmit").click(function(event){
//put here
			
			var currentPassword=$.trim($("#current_pasword").val());
			var newPassword=$.trim($("#new_pasword").val());
			var conPassword=$.trim($("#con_pasword").val());
			
		
            if(currentPassword.length<1){
				   alert("Please enter current password");
					event.preventDefault();
                 }
				else if(newPassword.length<1){
                   alert("Please enter new password");
                 event.preventDefault();
                }
				else if(conPassword.length<1){
                   alert("confirm your password");
               event.preventDefault();
                }
               else if(newPassword!=conPassword){
                  alert("Passwords do not match");
                 event.preventDefault();
                }
				else{
					showOutLoader();
					 var formData=new FormData();
					 formData.append('userId',$.trim($.session.get("globalUserID")));
					 formData.append('currentPassword',$.trim(currentPassword));
					 formData.append('newPassword',$.trim(newPassword));
					 
					  $.ajax({
						url:path+"pyxies/userservice/resetpassword",
						type: 'POST',
						data: formData,
						processData: false,
						contentType: false,
						success: function(responseData, textStatus, jqXHR) 
						{
								console.log(responseData);								
								 var stat=jQuery.parseJSON(responseData);
							if(stat.status=="success"){
							 //alert(stat.messsage);
							 alert("Your password is updated successfully");
							 $.mobile.changePage("index.html#home_page",{ 
												 transition: "fade",
												  changeHash: false 
												  });
							}
							else {
						       alert(stat.messsage);
							}
							hideLoader();
								
					   
						},
						error: function (responseData, textStatus, errorThrown) 
						{
										hideLoader();
										alert("Please try again after sometime!");
						}
					});
				}
  });
//--------------------------------saving a pyxie-----------------------------
$(document).on("pagebeforeshow","#pyxie_settings",function(){

	$('input[id=imgUpCheck][type="checkbox"]').prop('checked', false);
	$("input[id=update_st_of_pyxie]").prop('disabled', true);
	$("#hidthis").hide();
	
	$("#google_image_up").removeClass("google_on").addClass("google_off");
	$("#pinterest_image_up").removeClass("pinterest_on").addClass("pinterest_off");
	$("#flickr_image_up").removeClass("flickr_on").addClass("flickr_off");
	$("#youtube_image_up").removeClass("youtube_on").addClass("youtube_off");
	$("#vimeo_image_up").removeClass("vimeo_on").addClass("vimeo_off");
	$("#facebook_image_up").removeClass("facebook_on").addClass("facebook_off");
	$("#twitter_social_image_up").removeClass("twitter_on").addClass("twitter_off");
	$("#google_plus_image_up").removeClass("google_plus_on").addClass("google_plus_off");
	$("#instagram_image_up").removeClass("instagram_on").addClass("instagram_off");
	$("#cnn_image_up").removeClass("cnn_on").addClass("cnn_off");
	$("#bbc_image_up").removeClass("bbc_on").addClass("bbc_off");
	$("#times_image_up").removeClass("times_on").addClass("times_off");
	$("#google_news_image_up").removeClass("google_news_on").addClass("google_news_off");
	$("#feedzilla_image_up").removeClass("feedzilla_on").addClass("feedzilla_off");
	$("#imdb_image_up").removeClass("imdb_on").addClass("imdb_off");
	$("#bing_image_up").removeClass("bing_on").addClass("bing_off");
	$("#wikipedia_image_up").removeClass("wikipedia_on").addClass("wikipedia_off");

});

 $("#savePyxie").click(function(){  
//put here 
      var updatedNamePyxie=$("#update_name_pyxie").val();
	  var updatedSTPyxie=$("#update_st_of_pyxie").val();
	 
    var selected=$("input[type='checkbox'][name='imgUpCheck']:checked").length;
		    if(updatedNamePyxie.length<=2){
					 alert("Please Enter Valid Name of Pyxie");
					 event.preventDefault();
                  }
				  else if(selected<=1){
				  alert("Please select a source");
				  }
				  else{				  
				      				  
						var favorite="";
					   var bool=false;
								$.each($("input[name='imgUpCheck']:checked"), function(){ 
									if(!bool){
										favorite+=$(this).val();
										bool=true;
										}
										else{
										favorite+=","+$(this).val();
									}
								});
						
						var formData=new FormData();
						    formData.append('userid',$.trim($.session.get("globalUserID")));
							formData.append('pyxieId',particularPyxieId);
							formData.append('pyxiename',updatedNamePyxie);
							formData.append('search_item',updatedSTPyxie);
							formData.append('interest',favorite);
						
							if(updatePyxiePic==""){
											
							var url=path+"pyxies/pyxieservice/rest/pyxie/updatepyxie_with_out_image";
							updatePyxie(formData,url);
							}
							else{
						
								formData.append('pyxieImage',updatePyxiePic);							
								var url=path+"pyxies/pyxieservice/rest/pyxie/updatepyxie_with_image";
								updatePyxie(formData,url);
							}
							favorite.length = 0;
				  } 
     });
function updatePyxie(formData,url_new){
//put here
 showLoader();
                    $.ajax({
						   url:url_new,
						   type: 'POST',
			               data: formData,
			               processData: false,
			                contentType: false,
							  success: function(responseData, textStatus, jqXHR) 
							  {
							   var newUser=jQuery.parseJSON(responseData);
							   updatePyxiePic="";
							    console.log(newUser);
								hideLoader();
							    executePyxieInfo(newUser);					   
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {
							       hideLoader();
								alert("Please try again after sometime!");
							  }
							});
							
}
//-----------------------------------Deleting a Pyxie -------------------------------------------------------- 
	 $("#deletePyxie").click(function(){
             //put here
			  showLoader();
			  
			       var da={
						   "pyxieId" : particularPyxieId,
						   "user" : {"userId":$.trim($.session.get("globalUserID")) }
						   };
				  var dat= JSON.stringify(da);
				   $.ajax({ 
						  type: 'POST',
						   url: path+'pyxies/pyxieservice/rest/pyxie/deletepyxie',
						  data:dat,
						   contentType: "application/json; charset=UTF-8",
						 success: function(responseData, textStatus, jqXHR) 
						 {
							var response=jQuery.parseJSON(responseData);
						   alert(response.result);
						    hideLoader();
						   $.mobile.changePage("index.html#home_page",{ 
							  transition: "flip",
							   reverse: true, 
							   changeHash: false });
						   
						 },
						error: function (responseData, textStatus, errorThrown) 
						 {
						  hideLoader();
						alert("Please try again after sometime!");
						 }
				 });

			  });
	//-----------------------------Sharing a pyxie---------------------		  
	 var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div style="margin-bottom:3px;"><input type="text" id="getEmail'+x+'" placeholder="To" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
	$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
	
	$("#email_share").bind({
   popupbeforeposition: function(event, ui) {  	
		$("#getEmail").val("");
		$("#subject").val("Pyxie Application");
		$("#body").val("Pyxie is a great application,where you can find all your interests at one place.Please try it");
		if ($("#getEmail2").length){
		$("#getEmail2").val("");
		}
		if ($("#getEmail3").length){
		$("#getEmail3").val("");
		}
	
   }
});


$("#crtPyx").click(function(){
//put here
 $("#create_pyxie_button").css('display','none');
 $("#create_dummy_button").css('display','block');
	
$("#uploadPyxieImage").css('display','block');
  $("#uploadCropPyxieImage").css('display','none');
  $("#name_of_pyxie").val("");
   $("#serchterm_of_pyxie").val("");  
  $("#hidthis1").hide();
   
  $('input[type="checkbox"]').prop('checked', false);
$("#google_image").removeClass("google_on").addClass("google_off");
$("#pinterest_image").removeClass("pinterest_on").addClass("pinterest_off");
$("#flickr_image").removeClass("flickr_on").addClass("flickr_off");
$("#youtube_image").removeClass("youtube_on").addClass("youtube_off");
$("#vimeo_image").removeClass("vimeo_on").addClass("vimeo_off");
$("#facebook_image").removeClass("facebook_on").addClass("facebook_off");
$("#twitter_social_image").removeClass("twitter_on").addClass("twitter_off");
$("#google_plus_image").removeClass("google_plus_on").addClass("google_plus_off");
$("#instagram_image").removeClass("instagram_on").addClass("instagram_off");
$("#cnn_image").removeClass("cnn_on").addClass("cnn_off");
$("#bbc_image").removeClass("bbc_on").addClass("bbc_off");
$("#times_image").removeClass("times_on").addClass("times_off");
$("#google_news_image").removeClass("google_news_on").addClass("google_news_off");
$("#feedzilla_image").removeClass("feedzilla_on").addClass("feedzilla_off");
$("#imdb_image").removeClass("imdb_on").addClass("imdb_off");
$("#bing_image").removeClass("bing_on").addClass("bing_off");
$("#wikipedia_image").removeClass("wikipedia_on").addClass("wikipedia_off");

$.mobile.changePage("index.html#select_sources",{ 
							  transition: "slide", 
							   changeHash: false });

});

	$("#sendEmail").click(function(){
	
if(window.navigator.onLine){
    var emails=$.trim($("#getEmail").val());

			var formData=new FormData();  
			formData.append('from',$.trim( $.session.get("UserEmail")));	
				if(x>=2){
					emails+=",";
					emails+=$.trim($("#getEmail2").val());				
				} 
				if(x==3){
					emails+=",";
					emails+=$.trim($("#getEmail3").val());					
				}
				formData.append('to',emails);
				formData.append('subject',$.trim($("#subject").val()));
				formData.append('text',$.trim($("#body").val()));
		            $.ajax({
						   url:path+"pyxies/pyxieservice/rest/pyxie/sharepyxie",
						   type: 'POST',
			               data: formData,
			               processData: false,
			                contentType: false,
							  success: function(responseData, textStatus, jqXHR) 
							  {
							   console.log(responseData);
							   var data=jQuery.parseJSON(responseData);
							   		alert(data.mediaIds);			   
							  },
							  error: function (responseData, textStatus, errorThrown) 
							  {							   
									alert("Please try again after sometime!");
							  }
							});
          $("#email_share").popup("close");
	}
	else{
	alert("Please check your internet connection");
	}
	      							
	});
	
	$("#facebookShare").click(function(){
	
	if(window.navigator.onLine){
    var logtype=localStorage.getItem('loginType');
          //alert(logtype);
	 if($.trim(logtype)=="facebook"){
	        var urlPost="http://www.google.com";
			var message="testing";
			var url = "https://www.facebook.com/dialog/feed?app_id=752235481479350&link="+encodeURIComponent(urlPost)+"&caption=&description="+encodeURIComponent(message)+"&redirect_uri="+path+"pyxies/resources/success.html";
			
			 var ref = window.open(url, '', '');
	 }
	 else{
	 alert("Login with facebook");
	 } 
	}
	else{
	alert("Please check your internet connection");
	}
	
	 
	});
	
	$("#twitterShare").click(function(){
	if(window.navigator.onLine){
    var logtype=localStorage.getItem('loginType');
          //alert(logtype);
	 if($.trim(logtype)=="twitter"){
	 var urlPost="http://www.google.com";
	        var url='https://twitter.com/intent/tweet?text=hello+Pyxies&via=Pyxies&url='+encodeURIComponent(urlPost)+'&hashtags=Pyxies';
			 var ref = window.open(url, '', '');
	 }
	 else{
	 alert("Login with twitter");
	 }  
	}
	else{
	alert("Please check your internet connection");
	}
	
	});
	
	$("#gPlusShare").click(function(){
		if(window.navigator.onLine){
		  window.open("https://plus.google.com/share?url=http://www.google.com","","");
		}
		else{
		alert("Please check your internet connection");
		}
	});
	
	$("#pinShare").click(function(){
		if(window.navigator.onLine){
		  var urlPost="http://www.google.com";
		 var image="http://www.germanshepherdguide.com/uploads/1/4/7/0/14702016/8516346_orig.jpg";
		var url='http://pinterest.com/pin/create/button/?url='+encodeURIComponent(urlPost)+'&description=Pyxies+is+really+cool&media='+encodeURIComponent(image);
		var ref = window.open(url, '', '');
		}
		else{
		alert("Please check your internet connection");
		}
	});
	
	$("#gotoSocialPage").click(function(){
	$.mobile.changePage("#social_page", { 
									  transition: "fade",
									   changeHash: false });
	});
	loadBundles($.i18n.browserLang());
	 
	   // configure language combo box
        $('#lang').change(function() {
            selection = $('#lang option:selected').val();
			localStorage.setItem('language', $.trim(selection));
			//alert($.trim(selection)+" "+"in settings lang");
            loadBundles(selection !== 'browser' ? selection : $.i18n.browserLang());

                });
								
		 $('#lang1').change(function() {
			selection = $('#lang1 option:selected').val();
			
			localStorage.setItem('language', $.trim(selection));
			//alert($.trim(selection)+" "+"in main lang");
            loadBundles(selection !== 'browser' ? selection : $.i18n.browserLang());

            });
				
    $(document).on("pageshow","#general_settings",function(){
       //var seleted=localStorage.getItem('language');
	  // var mainSelection=$('#lang1 option:selected').val();
	  // var appSelection = $('#lang option:selected').val();
	 
	  $("#newEmail").val("");
	   $("#newPassword").val("");
	    $("#hide_acc").css("visibility","hidden");
	// alert($.trim(seleted)+" "+$.trim(mainSelection)+" "+$.trim(appSelection));
	  
    });
	 $("#login_new").click(function(){
	 //put here
			 var email=$('#newEmail').val();
			 var pass=$('#newPassword').val();
			 login(email,pass);
	 });
	 
	function login(email,pass){
	
	removeids();

	var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
if(email.length<1){
   alert("Email cannot be blank");
    //event.preventDefault();
  }
  else if(!regex.test(email)){
  alert("Please Enter Valid Email");
   //event.preventDefault();
  }
 else if(pass.length<1){
  alert("Password cannot be blank");
   //event.preventDefault();
  }
  else{
				    
					showOutLoader();
				var da={
					   "email":email,
						"password":pass
					   };
				  var dat= JSON.stringify(da);
				  $.ajax({ 
							  type: 'POST',
							  url: path+'pyxies/userservice/login',							  
							  data:dat,
							  crossDomain: true,
							  contentType: "application/json; charset=UTF-8",															                            							
							  success: function(responseData, textStatus, jqXHR){							  
								 console.log(responseData);
								  var obj = jQuery.parseJSON(responseData);
								  console.log(obj.status);						
								  if(obj.status=="success"){								  
                                 $.session.set("globalUserID",$.trim(obj.userId));
								  localStorage.setItem('gui', $.trim(obj.userId));
								  localStorage.setItem('loginType','email');
								  $("#profile_name").text(obj.fname);
								   $.session.set("UserEmail",$.trim(obj.emailId));								  
								   setProfileImage(obj);
								  //getTopFivePyxiesofUser(obj.profile_data.user_id);
								  hideOutLoader();
								  	if($.session.get("firstLogin") != 'true'){
										   $.session.set("firstLogin",'true'); 
										   $.mobile.changePage("#How_To_Use", { 
															  transition: "fade",
															   changeHash: false });
									}else{
									   $.mobile.changePage("index.html#home_page",{ 
										  transition: "fade",
										  changeHash: false });
									}

								  }
								  else if(obj.status=="fail"){
                                    hideOutLoader();						  
									alert("Please Enter Correct Email/Password");
									$("#login_password").val("");
								  }
						   },
							  error: function (responseData, textStatus, errorThrown) 
								  {
								  hideOutLoader();
                                alert("Please try again after sometime!");
							
								 }
					});
		}
	}
    
   function removeids(){
       $('#first_top_pyxie').css('background-image', "");	
        $('#first_top_pyxie').attr('data-id',"");      	
		$('#first_top_pyxie_name').text("pyxie 1");
		$('#second_top_pyxie').css('background-image', "");	
        $('#second_top_pyxie').attr('data-id',"");		
		$('#second_top_pyxie_name').text("pyxie 2");	
        $('#third_top_pyxie').css('background-image', "");
		$('#third_top_pyxie').attr('data-id',"");
		$('#third_top_pyxie_name').text("pyxie 3");
		$('#forth_top_pyxie').css('background-image', "");
		$('#forth_top_pyxie').attr('data-id',"");
		$('#forth_top_pyxie_name').text("pyxie 4");
		$('#fifth_top_pyxie').css('background-image', "");
		$('#fifth_top_pyxie').attr('data-id',"");	
		$('#fifth_top_pyxie_name').text("pyxie 5");
   }
   
   function removeCountryWorld(){
	$('#first_country_pyxie').css('background-image', "");									    
	$('#first_country_pyxie').attr('data-id',"");
	$('#first_country_pyxie_name').text("");

	$('#second_country_pyxie').css('background-image', "");									
	$('#second_country_pyxie').attr('data-id',"");
	$('#second_country_pyxie_name').text("");

	$('#third_country_pyxie').css('background-image', "");									 
	$('#third_country_pyxie').attr('data-id',"");
	$('#third_country_pyxie_name').text("");

	$('#forth_country_pyxie').css('background-image', "");
	$('#forth_country_pyxie').attr('data-id',"");
	$('#forth_country_pyxie_name').text("");	

	$('#fifth_country_pyxie').css('background-image', "");							  
	$('#fifth_country_pyxie').attr('data-id',"");
	$('#fifth_country_pyxie_name').text("");
   }
  	
  function loadBundles(lang) {
                $.i18n.properties({
                    name: 'Messages',
                    path: 'bundle/',
                    mode: 'both',
                    language: lang,
                    callback: function() {
                        //$("#msg_welcome").text($.i18n.prop('msg_welcome'));
                        $("#sign_in_with").text(sign_in_with);
                        $("#pyxie_caption").text(pyxie_caption);
						$("#pyxie_caption_second_line").text(pyxie_caption_second_line);
						 
						$("#email_login").text(email_login);
						$("#email_signup").text(email_signup);
						$("#register").text(email_login);
						$("#continueButton").text(continueButton);
						$("#backreg").text(backreg);
						$("a[id=sign_back]").text(backreg);
						$("#for_pass").text(for_pass);
						$("#for_pass1").text(for_pass);
											
						$("#submit").text(submit);
						$("#chsubmit").text(submit);
						$("#ch_pass").text(ch_pass);
						$("#ch_pass1").text(ch_pass);
						$('#current_pasword').attr("placeholder",current_pasword);
						$('#new_pasword').attr("placeholder",new_pasword);
						$('#con_pasword').attr("placeholder",registration_confirmpassword);
						
						$("#maintc").text(maintc);						
						$("#tnc").text(tnc);
						$("#restTnc").text(restTnc);
						$("#termsCond").text(termsCond);
						$("#actCond").text(actCond);
						
						$('#login_email').attr("placeholder",registration_email);
						$('#login_password').attr("placeholder",registration_password);
						$('#plsenter').attr("placeholder",plsenter);
						
						$('#registration_username').attr("placeholder",registration_username);
						$('#registration_email').attr("placeholder",registration_email);
						$('#registration_password').attr("placeholder",registration_password);
						$('#registration_confirmpassword').attr("placeholder",registration_confirmpassword);

						$('#newEmail').attr("placeholder",registration_email);
						$('#newPassword').attr("placeholder",registration_password);
						
						$('#name_of_pyxie').attr("placeholder",name_of_pyxie);
						$('#serchterm_of_pyxie').attr("placeholder",serchterm_of_pyxie);
						$("#update_name_pyxie").attr("placeholder",name_of_pyxie);
						
						$("a[id=friends_name]").text(friendsPyxies);
						$("a[id=add_name]").text(addPyxies);
						$("#ad_py").text(addPyxies);
						
						$("a[id=all_name]").text(allPyxies);

						$('#getEmail').attr("placeholder",getEmail);
						$('#subject').attr("placeholder",subject);
						$('#body').attr("placeholder",body);
						//$('input[type="button"][id=loadmoreImages]').text(pyxMore);
						
                        $("#my_top_5").text(my_top_5);						
						$("#friendsPyxies").text(friendsPyxies);
						$("#addPyxies").text(addPyxies);
						$("#allPyxies").text(allPyxies);
						$("#profSet").text(profSet);
						$("#editinfo").text(editinfo);
						$("#pyxSet").text(pyxSet);
						$("#addmoreMedia").text(addmoreMedia);
						
						$("#resize1").text(resize);
						$("#resize2").text(resize);
						$("#resize3").text(resize);
						$("#resize4").text(resize);
						   
						$("#goToUploadPic").text(crop);
						$("#goToProfileSettings").text(crop);
						$("#goToSelectSources").text(crop);
						$("#gobackPyxieSettings").text(crop);
						$("#lngmain").text(lng);						 
						$("#gotoSocialPage").text(done);
						
						$("#edit_button").text(edit_button);
						$("#del_pyx").text(del_pyx);
						$("#savePyxie").text(savePyxie);
						$("#deletePyxie").text(yes);
						$("#canceldelete").text(no);
						$("#addmorefields").text(addmorefields);
						$("#sendEmail").text(sendEmail);						
						$("#sav_pyx").text(sav_pyx);
						$("#watch_video").text(watch_video);
												
						$("#upname").text(name_of_pyxie);
						$("#upsrch").text(serchterm_of_pyxie);
												  
						$("#pyxImages").text(pyxImages);
						$("#pyxVideos").text(pyxVideos);
						$("#pyxSocial").text(pyxSocial);
						$("#pyxNews").text(pyxNews);
						$("#pyxMore").text(pyxMore);
						$("#done2").text(done);
						
						$("a[id=img_tab]").text(pyxImages);
						$("a[id=vid_tab]").text(pyxVideos);
						$("a[id=soc_tab]").text(pyxSocial);
						$("a[id=news_tab]").text(pyxNews);
						$("a[id=more_tab]").text(pyxMore);
						
						$("#areYouSure").text(areYouSure);
						$("#sharePyx").text(sharePyx);
						$("#shareon").text(shareon);
						
						$("#menu_nav").text(menu_nav);
						$("#mytop_nav").text(mytop_nav);
						$("#allmy_nav").text(allmy_nav);
						$("#add_nav").text(add_nav);
						$("#friends_nav").text(friends_nav);
						$("#gen_nav").text(gen_nav);
						$("#info_nav").text(info_nav);
						$("#howto_nav").text(howto_nav);
						$("#logout").text(logout);
						
						$("#Allmytext").text(allPyxies);
						$("#AddPyx").text(addPyxies);
						$("#add").text(add);
					    $("#top5").text(top5);
						$("#frenpyx").text(friendsPyxies);
						$("#frenpyx1").text(friendsPyxies);
						
						$("#srchPyx").text(serchPyx);
						$("#crtPyx").text(createpyx); 
						$("#world").text(world);
						$("#country").text(country);
						$("#create_pyxie_button").text(create_pyxie_button); 
                        $("#create_dummy_button").text(create_pyxie_button);						
						
						$("#infoPyx").text(infoPyx);
						$("#maininfo").text(maininfo);
						$("#maininfo1").text(maininfo);
						$("#genSet").text(gen_nav);
						
						$("#lng").text(lng);
						$("#priv").text(priv);
						$("#sharepyx").text(sharepyx);
						$("#lnge").text(lng);
						$("#howt").text(howto_nav);
						$("#howt1").text(howto_nav);
						$("#inst").text(inst);
						$("#serchPyx").text(serchPyx);
						
						$("#createpyx").text(createpyx);
						$("#whatyll").text(whatyll);					
						$("#sel2").text(goToCreatePyxie);
						$("#greet").text(greet);
						
						$("#pyxImgcre").text(pyxImages);
						$("#pyxVidcre").text(pyxVideos);
						$("#pyxSoccre").text(pyxSocial);
						$("#pyxNewcre").text(pyxNews);
						$("#pyxMorcre").text(pyxMore);
						
						$("#change_acc").text(change_acc);
						$("#another_acc").text(another_acc);
						$("#login_new").text(login_new);
						

                    }
                });
            }

		$('.fancybox').fancybox();
				$(".fancybox")
						.attr('rel', 'gallery')
						.fancybox({
							openEffect  : 'none',
							closeEffect : 'none',
							nextEffect  : 'none',
							prevEffect  : 'none',
							padding     : 0,
							margin      : [30,2,30,2] 
							
						});
				
			
				$(window).on("orientationchange",function(event){
				
				  if($.trim(event.orientation)=="landscape")
				  {
					  $(".fancybox")
					.attr('rel', 'gallery')
					.fancybox({
						openEffect  : 'none',
						closeEffect : 'none',
						nextEffect  : 'none',
						prevEffect  : 'none',
						padding     : 0,
						margin      : [10,10,10,10] // Increase left/right margin
					});
				 }
				 else{
						 $(".fancybox")
						.attr('rel', 'gallery')
						.fancybox({
							openEffect  : 'none',
							closeEffect : 'none',
							nextEffect  : 'none',
							prevEffect  : 'none',
							padding     : 0,
							margin      : [30,2,30,2] 
						});
				 }
		});
	
});//main

$(document).on("pageshow","#home_page",function(){ 
             $("[data-role=panel]").panel().enhanceWithin();
			 var header = $('[data-role=header]').outerHeight();
			var panel = $('.ui-panel').height();
            var footer = $('[data-role=footer]').outerHeight();
			var panelheight = panel - (header+footer);
			
			$('.ui-panel').css({
				'top': header,
				'bottom':footer
			});
			
		});

$(document).on('pageinit','#splash',function(){ 

  
  $("#splash_screen_image").attr("height",$(window).height()+"px");
  
    setTimeout(function(){
		   var gui=$.trim($.session.get("globalUserID"));
             var okok=$.trim(localStorage.getItem('gui'));
			 var lang=$.trim(localStorage.getItem('language'));
		   
		   if(gui==""&&okok==""){
		   
				  if(lang==""){
				  $.mobile.changePage("#language_page", { 
											  transition: "fade",
											  changeHash: false });
				  }
				  else{				 
				  $.mobile.changePage("#social_page", { 
											  transition: "fade",
											  changeHash: false });
				  }
		 
		  }
		 else{
		 $.session.set("globalUserID",okok); 
		 if(localStorage.getItem('loginType')=="twitter"){
		 
		 $.mobile.changePage("#social_page", { 
											  transition: "fade",
											   changeHash: false });
		 }
		 else{
		 
		 $.mobile.changePage("#home_page", { 
											  transition: "fade",
											   changeHash: false });
		 }
				}		   
				   }, 3000);

});

$(document).bind("mobileinit", function(){
    $.mobile.page.prototype.options.domCache = false;
});