/* GIGYA */
jQuery(document).ready(function() {

    if(typeof(gigya) !== "undefined") {

       var connectedUserInfo = null;

       /**
        * function to return the name for a connected user
        * user gigya user object
        */
       function getConnectedUserName(user){
           var senderName = null;

           if (user.firstName){
               senderName = user.firstName;
           }

           if (user.lastName){
               senderName = (senderName) ? senderName + ' ' + user.lastName : user.lastName
           }

           return senderName;
       }

       /* Publish an activity internally (only to site scope)
		* This method is associated with taking an action on the site
        */
	   function publishFeed(params) { console.debug(params);
			// Constructing a UserAction Object
			var act = new gigya.services.socialize.UserAction();
			act.setUserMessage(params.userMsg);        // Setting the User Message
			act.setLinkBack(params.linkBack);          // Adding a linkBack
			act.setTitle(params.title);                // Setting the title
			act.setDescription(params.description);    // Setting the Description

            if (params.src != '' && params.type != ''){
                act.addMediaItem({              // Adding a Media
                    'src': params.src,
                    'href': params.linkBack,
                    'type': params.type
                 });
            }

            if (typeof(params.scope) == 'undefined' ) params.scope = 'internal';
            if (typeof(params.privacy) == 'undefined') params.privacy = 'public';

			// Parameters for the publishUserAction method,
			var publishFeedParams = {
				userAction:act,
				scope:params.scope,
				privacy:params.privacy
			};

            if (typeof(params.feedID) !== 'undefined') publishFeedParams.feedID = params.feedID;

			// Publish the User Action
   			gigya.services.socialize.publishUserAction(conf, publishFeedParams);
       }

       /** Get Gigya Short URL */
       function gigyaShortURL(assetURL){
         var params   = {callback: function(response){
						if ( response.errorCode == 0 ) {
							shortURL = response.shortURL;
						}
						else {
							shortURL = null;

							if (typeof (console) !== "undefined"){
								console.debug('Short URL Error: ' + response.errorMessage);
							}
						}
				   },
				   URL: assetURL
			  };

          if (assetURL){
              gigya.services.socialize.shortenURL(conf, params );
          }
       }


	    // Callback for comment count
	    function showCommentCount(response) {
			if (response.errorCode == 0) {
				var comments = jQuery('span.cc-'+response.context.id).html();
				comments = parseInt(comments) + parseInt(response.streamInfo.commentCount);
				jQuery('span.cc-'+response.context.id).html(comments);				
			}
			else {console.log(response.errorCode+' '+response.errorMessage);}
	    }
	   
       // Callback to handle e-mail share and other share actions
       function shareBarCallback(event){
	   
            if (event.providers == "email"){
                //update emailed table in ugc
                var recipis = [];
                for(var i=0;i < event.recipients.length;i++){
                    recipis.push(event.recipients[i].email);
                }

                var senderName  = event.sender;
                var senderEmail = ' ';
                var senderUUID  = (jQuery.cookie('sso')) ? jQuery.cookie('sso') : null;

                if (typeof webuser !== 'undefined' && webuser.uuid){
                  senderUUID = webuser.uuid;
                }
/*
                //if connected
                if (typeof connectedUserInfo !== 'undefined' && connectedUserInfo){
                    senderName  = getConnectedUserName(connectedUserInfo);
                    if (!senderName) senderName = event.sender;

                    if (connectedUserInfo.email != ''){
                        senderEmail  = connectedUserInfo.email;
                    }
                }

                var emailData = {
                                message:event.userMessage,
                                assetId:event.context.id,
                                assetTitle:event.context.title,
                                assetUrl:event.context.location,
                                senderEmail:senderEmail,
                                senderUUID:senderUUID,
                                senderName:senderName,
                                recipientEmail:recipis.join(),
                                assetType:event.context.classname,
                                assetTeaser:event.context.teaser,
                                siteName:event.context.siteName
                              };


                jQuery.ajax({
                    url:'/common/php/ajax/insertAssetEmail.php',
                    data:emailData,
                    dataType:'json'
                });
            
*/
			}
            //publish action to activity feed
            publishFeed({userMsg: event.userMessage + ' on ' + event.providers,
                        linkBack: jQuery('div.'+event.context.id+' .post-location').val(),
                        title: 'Shared ' + jQuery('div.'+ event.context.id+' .post-title').val(),
                        description: jQuery('div.'+event.context.id+' .post-summary').val(),
                        srcType:'image',
                        src:jQuery('#firstPhotoURL').val()
                       });
        }
			

        // Callback to handle comment submission
        function commentCallback(event){
            var userName, userEmail,guestUser;

            if(event.guestUser){
                userName = event.guestUser.nickname;
                userEmail = event.guestUser.email;
                guestUser = 1;
            }
            else if(event.user){
                userName  = event.user.firstName + ' ' + event.user.lastName;
                userEmail = event.user.email;
                guestUser = 0;
            }
/*
            var commentData = {
                                commentText:event.commentText,
                                assetId:event.context.id,
                                assetTitle:event.context.title,
                                assetUrl:event.context.location,
                                userName:userName,
                                userEmail:userEmail,
                                assetType:event.context.classname,
                                assetTeaser:event.context.teaser,
                                siteName:event.context.siteName,
                                gigyaComment:1,
                                guestUser:guestUser,
                                adminConsoleId:event.context.adminConsoleId
                              };
            jQuery.ajax({
                url:'/common/php/ajax/insertSitesadminComment.php',
                data:commentData,
                dataType:'json',
                success:function(response){
                    if (response != 0 && parseInt(response, 10) == response){
                        var divElm     = jQuery('div.shareCommentsCount');
                        var spanElm    = jQuery(divElm).find('span.comment-count-generated');
                        spanElm.html(response)
                        divElm.css('display', 'block');
                    }
                }
            });
*/
            //publish to activity feed
            publishFeed({userMsg:   event.commentText,
                        linkBack:   jQuery('.post-location').val(),
                        title:      'Commented on ' + jQuery('.post-title').val(),
                        description: jQuery('.post-summary').val()
                       });
        }

       //when a new connection is added run update
       function update(res){
            connectedUserInfo = res.user;  //capture user information
			             //only do this if we don't already have their email
			if((res.provider === "twitter" || res.provider === "linkedin") && (webuser.email == undefined || webuser.email === null)){
			   jQuery("#socialpopup").load('/wp-content/themes/TR/gigya-additional-email.php', {firstname:res.user.firstName, lastname:res.user.lastName,icon:res.user.thumbnailURL})
                .dialog({
                autoOpen:   false,
                modal:      true,
                //bgiframe:   true,
                draggable:  false,
                resizable:  false,
                position:   'center',
                hide:       'fold',
                closeOnEscape: false,
                open: function(event, ui) { jQuery(".ui-dialog-titlebar-close").hide(); }
                })
                .dialog('option', 'title', '<strong>Additional Information Request</strong>')
                .dialog('option', 'buttons', {
                    "Ok": function() {
                        var $formVal = jQuery(this).find("form");
                        $formVal.validate({
                            errorClass: "social-popup-error",
                            rules:{
                                email: {
                                    required:true,
                                    email:true
                                }
                            }
                        });
                        if($formVal.valid()) {
                            res.user.email = jQuery('#social-email-addition').val();
                            if(res.provider === "twitter"){
                                res.user.identities.twitter.email = res.user.email;
                            }else if(res.provider === "linkedin"){
                                res.user.identities.linkedin.email = res.user.email;
                            }
                            jQuery(this).dialog("close");
                            updateWSD(res); //update WSD
                        }
                    }
                })
                .dialog("open");

           }
            updateUI(res);
            updateWSD(res); //update WSD
			document.cookie = "gigyaUpdate=true;path=/";//set cookie to update session when a page is loaded
       }

       //when connection is added/removed update UI
       function updateUI(res){
             var editElm = null;

             if (jQuery('#socialLoginContainer').length > 0){
                var socialLoginContElm =  jQuery('#socialLoginContainer');

                 if (typeof res.user !== 'undefined' && res.user.isConnected){
                        if (!connectedUserInfo){
                            connectedUserInfo = res.user;
                        }

                        editElm = socialLoginContElm.find('#editconnect');

                        if (!editElm.length){
                            socialLoginContElm.find('span.connect').css('display','none');
                            socialLoginContElm.prepend('<a id="editconnect" class="edit" href="#">Edit</a>');
                            editElm = jQuery('#editconnect');
                            editElm.unbind('click');
                            editElm.bind('click', function() {
                                editConnections();
                                return false;
                            });
                            editElm.bind('focus', function(){jQuery(this).blur();})
                        }
                 }
                 else {
                    connectedUserInfo = null;
                    editElm = jQuery("#socialLoginContainer #editconnect");

                    if (editElm.length > 0){
                        editElm.remove();
                        jQuery('#socialLoginContainer span.connect').css('display','block');
                    }
                 }
             }
       }

       //when a new connection is added push content to wsd
       function updateWSD(res){
			if(res.user.email != '' && res.user.email != null){
			console.log(res);
                //like registrar call a script and pass in paramters to get aroung xss blocks
                var html_doc = document.getElementsByTagName('head')[0];
                var js = document.createElement('script');
                js.setAttribute('type', 'text/javascript');
                js.setAttribute('src', wsdWebServiceUrl+'/webuser/addFromGigya/?uuid='+webuser.uuid+'&user='+jQuery.toJSON(res.user.identities)+'&si='+site.adminConsoleId);
                html_doc.appendChild(js);
				webuser.email = res.user.email //update golbal webuser with email to prevent email popup
            }

           //push res.user to wsd?
       }

        // error handler
        function errorCallback(event) {
            gigyaMessageDebug('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
        }

        // Callback method to handle published reaction
        function reactionCallback(event){
           //publish to activity feed
		  
           publishFeed({userMsg: event.userMessage + ' on ' + event.providers,
                        linkBack: jQuery('.post-location').val(),
                        title: 'Reacted on ' + jQuery('.post-title').val(),
                        description: jQuery('.post-summary').val(),
                        srcType:'image',
                        src:jQuery('#firstPhotoURL').val()
                       });

        }

        /** add connections **/
        function addConnections(){
            var addConnectionsUIParams = {
                                         showTermsLink:false,
                                         showEditLink:false,
                                         hideGigyaLink:true,
                                         containerID:'socialLogin',
                                         showTooltips:true,
                                         height:40,
                                         width:140,
                                         UIConfig: '<config><body><controls><snbuttons buttonsize="15"></snbuttons></controls></body></config>',
                                         cid:'sociallogin',
                                         onLoad:function(event){
                                                    jQuery('#socialLoginContainer span.connect').css('display','block');
                                                },
                                         onError: errorCallback
                                       };

                gigya.services.socialize.showAddConnectionsUI(conf, addConnectionsUIParams);
        }

        /** edit connections **/
        function editConnections(){
          var editConnectionsUIParams = {
                                         showTermsLink:false,
                                         showEditLink:false,
                                         hideGigyaLink:true,
                                         showTooltips:true
                                       };

          gigya.services.socialize.showEditConnectionsUI(conf, editConnectionsUIParams);
        }

        /** debug message **/
        function gigyaMessageDebug(message){
            if (typeof console !== 'undefined' && message){
                console.debug(message);
            }
        }

        /** Social connect **/
        if (jQuery('#socialLoginContainer').length > 0)  {
            addConnections();
        }


        /** Share Bar **/
        if (jQuery('#share').length > 0){
            var act = new gigya.services.socialize.UserAction(),
            shareList = [{'provider':'share','tooltip':'Share'}];

			var id = jQuery('#share').attr('class');
			
            //gigya methods - get values from hidden fields
            act.setUserMessage("Checkout this great piece I read on Teleread");
            act.setTitle(jQuery('.post-title').val());
            act.setLinkBack(jQuery('.post-location').val());
            act.setDescription(jQuery('.post-summary').val());
            act.addActionLink("Read More", jQuery('.post-location').val());

            // Adding a Media (image/flash/mp3)
            var mediaShare = null;
            if (jQuery('#itemPath').length > 0){
					if ( jQuery('#itemPhoto').html() !== ''){
                            mediaShare = {
                                        type: 'image',
                                        src:  jQuery('#itemPhoto').html(),
                                        href: jQuery('#location').val()
                                    };
                    }
            }
            else if (jQuery('#firstPhotoURL').val()){
                    mediaShare = {
                        type: 'image',
                        src:  jQuery('#firstPhotoURL').val(),
                        href: jQuery('#location').val()
                    };
           }

           //attach media
           if (mediaShare){
               act.addMediaItem(mediaShare);
           }

           //for each share option selected in widget, add to array
           jQuery('#share ul li').each(function(){
                //store elem class
                var elemClass      = jQuery(this).attr('class');
                var elemText       = jQuery(this).find('a').text();

                //create a valid list of share providers
				var shareProviders = conf.enabledProviders;
				shareProvidersArr  = shareProviders.split(',');
				shareProvidersArr.push('e-mail','email');

                var tooltip = 'Share using ';

                //if there are multiple classes, split and check each one and ignore the first-child class
                if(elemClass.indexOf(' ') !== -1) {
                    var classArr = elemClass.split(' ');
                    for(cls in classArr){
                        //ignore first-child class
                        if(jQuery.inArray(classArr[cls], shareProvidersArr) !== -1) {
                            //convert e-mail to email
                            if(classArr[cls] === "e-mail") {classArr[cls] = "email"}
                            tooltip = tooltip + elemText;
                            shareList.push({'provider':classArr[cls],'tooltip':tooltip});
                        }
                    }
                }
                else {
                    if(jQuery.inArray(elemClass, shareProvidersArr) !== -1) {
                        if(elemClass === "e-mail") {elemClass = "email"}
                        tooltip = tooltip + elemText;
                        shareList.push({'provider':elemClass,'tooltip':tooltip});
                    }
                }
            });

            //set up params
            var shareBarParams =
            {
              userAction: act,
              containerID: 'share',
              shareButtons: shareList,
              showSuccessMessage:true,
              cid:jQuery('#assetType').val(),
              context: {location:jQuery('.post-location').val(),
                         title:jQuery('.post-title').val(),
                         teaser:jQuery('.post-summary').val(),
                         date:jQuery('#date').val(),
                         id:id,
                         classname:jQuery('#assetType').val(),
                         siteName:jQuery('#site-title').val()},
              onSendDone: shareBarCallback,
              onError: errorCallback,
              iconsOnly:true,
              noButtonBorders:false,
			  emailProviders:'yahoo,google'
            };

            //render top share
            shareBarParams.onLoad  = function(event){
                                          var width = parseInt(jQuery('#share').css('width'),10);
                                          jQuery('#share').css({'visibility':'visible','width':width});
                                          //jQuery('#shareDivContainer').css('display','block');
                                     }

            gigya.services.socialize.showShareBarUI(conf,shareBarParams);

            //copy previous object and change containerID property
            
			var shareBarParamsBottom         = jQuery.extend({},shareBarParams);
            shareBarParamsBottom.containerID = 'share-bottom';
            shareBarParamsBottom.onLoad      = function(event){
                                                  var width = parseInt(jQuery('#shareDivBottom').css('width'),10);
                                                  jQuery('#share-bottom').css({'visibility':'visible','width':width});
                                                  //jQuery('#shareDivContainerBottom').css('display','block');
                                                }

            //render bottom share
            gigya.services.socialize.showShareBarUI(conf, shareBarParamsBottom);
			
			var params = {
				categoryID: "Teleread",
				streamID: jQuery('.post-location').val(),
				context: {id:id}
				//callback: showCommentCount
			};
			
			gigya.services.comments.getStreamInfo(conf,params);
			
        }
		
		
		/** Multi-Share Bar **/
        if (jQuery('.share').length > 0){
		jQuery('.share').each(function() {
            var act = new gigya.services.socialize.UserAction(),
            shareList = [{'provider':'share','tooltip':'Share'}];

			var id = jQuery(this).attr('id');
			
			var location = jQuery('div.'+id+' .post-location').val();
			var title = jQuery('div.'+id+' .post-title').val();
			var summary = jQuery('div.'+id+' .post-summary').val();
			
			
            //gigya methods - get values from hidden fields
            act.setUserMessage("Checkout this great piece I read on Teleread");
            act.setTitle(title);
            act.setLinkBack(location);
            act.setDescription(summary);
            act.addActionLink("Read More", jQuery('div.'+id+' .post-location').val());

            // Adding a Media (image/flash/mp3)
            var mediaShare = null;
            if (jQuery('#itemPath').length > 0){
					if ( jQuery('#itemPhoto').html() !== ''){
                            mediaShare = {
                                        type: 'image',
                                        src:  jQuery('#itemPhoto').html(),
                                        href: jQuery('#location').val()
                                    };
                    }
            }
            else if (jQuery('#firstPhotoURL').val()){
                    mediaShare = {
                        type: 'image',
                        src:  jQuery('#firstPhotoURL').val(),
                        href: jQuery('#location').val()
                    };
           }

           //attach media
           if (mediaShare){
               act.addMediaItem(mediaShare);
           }

           //for each share option selected in widget, add to array
		    
           jQuery(this).find('li').each(function(){
                //store elem class
                var elemClass      = jQuery(this).attr('class');
                var elemText       = jQuery(this).find('a').text();

                //create a valid list of share providers
				var shareProviders = conf.enabledProviders;
				shareProvidersArr  = shareProviders.split(',');
				shareProvidersArr.push('e-mail','email');

                var tooltip = 'Share using ';

                //if there are multiple classes, split and check each one and ignore the first-child class
                if(elemClass.indexOf(' ') !== -1) {
                    var classArr = elemClass.split(' ');
                    for(cls in classArr){
                        //ignore first-child class
                        if(jQuery.inArray(classArr[cls], shareProvidersArr) !== -1) {
                            //convert e-mail to email
                            if(classArr[cls] === "e-mail") {classArr[cls] = "email"}
                            tooltip = tooltip + elemText;
                            shareList.push({'provider':classArr[cls],'tooltip':tooltip});
                        }
                    }
                }
                else {
                    if(jQuery.inArray(elemClass, shareProvidersArr) !== -1) {
                        if(elemClass === "e-mail") {elemClass = "email"}
                        tooltip = tooltip + elemText;
                        shareList.push({'provider':elemClass,'tooltip':tooltip});
                    }
                }
				
			});
			
            //set up params
            var shareBarParams =
            {
              userAction: act,
              containerID: jQuery(this).attr('id'),
              shareButtons: shareList,
              showSuccessMessage:true,
              cid:jQuery(this).attr('id'),
              context: {location:location,
                         title:title,
                         teaser:summary,
                         date:jQuery('#date').val(),
                         id:id,
                         classname:'blog',
                         siteName:'Teleread'},
              onSendDone: shareBarCallback,
              onError: errorCallback,
              iconsOnly:true,
              noButtonBorders:false,
			  emailProviders:'yahoo,google'
            };

            //render top share
            shareBarParams.onLoad  = function(event){
                                          var width = parseInt(jQuery(this).css('width'),10);
                                          jQuery(this).css({'visibility':'visible','width':width});
                                          //jQuery('#shareDivContainer').css('display','block');
                                     }

            gigya.services.socialize.showShareBarUI(conf,shareBarParams);
	
			var params = {
				categoryID: "Teleread",
				streamID: location,
				context: {id:id}
				//callback: showCommentCount
			};
			
			gigya.services.comments.getStreamInfo(conf,params);
			
			});
        }

        /** Comments **/
        //jQuery('#archived-comments-display .gigyaComment').each(function(){
        //    jQuery(this).hide();
        //});
		/*
		jQuery('#respond').hide();

        if (jQuery('#comments').length > 0){
            //hide link to show form and insert comments into comment-display div
            jQuery('#leave-comment').css('display','none');

            var showCommentsUI_params =
            {
                categoryID: 'Teleread',
                streamID: jQuery('.post-location').val(),
                containerID: 'comments',
                cid:'blog',
                context: { location:jQuery('.post-location').val(),
                           title:jQuery('.post-title').val(),
                           teaser:jQuery('.post-summary').val(),
                           date:jQuery('#date').val(),
                           id:jQuery('#sid').val(),
                           classname:jQuery('#assetType').val(),
                           siteName:jQuery('#site-title').val(),
                           adminConsoleId:site.adminConsoleId
                         },
                onCommentSubmitted: commentCallback,
                onError:errorCallback,
                width:635
            }

            if(showCommentsUI_params.cid == 'blog'){
                showCommentsUI_params.width = 450;
            }

            gigya.services.socialize.showCommentsUI(conf,showCommentsUI_params);

            //if there are archived comments show divs
            if(jQuery('#archived-comments').children('.comment').size() > 0){
                jQuery('#archived-comments').show();
                //jQuery('#archived-comments-display').show();
            }
        }

         //toggle for archived comments
		 
        var aflip = 1;
        var linkText = ["Click here to hide archived comments...","Click here to view archived comments..."]
        jQuery('#view-comments').text(linkText[0]);
        jQuery("#view-comments").click(function () {
            var toggleNum = aflip++ % 2;
            jQuery("#archived-comments").toggle( toggleNum == 0 );
            jQuery(this).text(linkText[toggleNum]);
            return false;
        });
		*/

        /** Event sharing **/
        //show share popup when gigya-share event is fired
        jQuery(document).bind('gigya-share', function(params){
			var eventact = new gigya.services.socialize.UserAction();
            var cid      = (params.cid) ? params.cid : null; //set the context id
            var publishMessage = null; //activity feed message

			eventact.setUserMessage(params.message);
			eventact.setTitle(params.title);
			eventact.setLinkBack(params.linkBack);
			eventact.setDescription(params.description);

			// Adding a Media (image)
			if (params.src && params.srcType){
				eventact.addMediaItem( {
					type: params.srcType,  // Type of the media (image/flash/mp3)
					src:  params.src,      // URL to the image source
					href: params.linkBack  // URL to redirect the user when he clicks the image
				});
			}

            //set the activity feed message
            publishMessage = (params.publishMessage) ? params.publishMessage + ': ' + eventact.title : eventact.title;

            var shareUIParams  = {
                                 userAction:eventact,
                                 cid:cid,
                                 showAlwaysShare:'unchecked',
                                 autoShareActionID:'event-share',
                                 onSendDone:function(a){
                                                //Publish to activity feed
                                                publishFeed({userMsg: a.userMessage + ' on ' + a.providers,
                                                             linkBack: params.linkBack,
                                                             title: publishMessage,
                                                             description: params.description});
                                            }
                               };

			gigya.services.socialize.showShareUI(conf, shareUIParams);

		});
		
		jQuery('form#postform').submit(function() {
			if (!jQuery(this).attr('shared')) {
				var title = jQuery(this).find('input#topic').attr('value');
				var post = jQuery(this).find('textarea#post_content').attr('value');
				
				if (title != '' &&  post != '') {
					jQuery(document).trigger({
						type:'gigya-share',
						message:'Your message',
						title:title,
						linkBack:'http://'+document.domain+'/topic/'+title.replace(' ','-'),
						description:post,
						publishMessage:'New Discussion',
						content:'new-discussion',
						cid:'new-discussion',
						form:jQuery(this)
					});
				}
				jQuery(this).attr('shared', 1);
				return false;
			}
			return true;
		});

        //trigger gigya event when newsletter or magazing signup event is fired
		jQuery(document).bind('newsletter-signup', function(event, data){
                jQuery(this).trigger({
                    type:"gigya-share",
                    message:"Your message",
                    title:data.title,
                    linkBack:data.linkBack,
                    description:data.description,
                    srcType:data.srcType,
                    src:data.src,
                    publishMessage:'Subscribed',
                    context:'newsletter-signup',
                    cid:'newsletter-signup'
                });
		});

		jQuery(document).bind('magazine-signup', function(event, data){
			jQuery(this).trigger({
				type:"gigya-share",
				message:"Your message",
				title:data.title,
				linkBack: data.linkBack,
				description:data.description,
                srcType:data.srcType,
                src:data.src,
                publishMessage:'Subscribed',
                context:'magazine-signup',
                cid:'magazine-signup'
			});
		});

        /* Reactions */
       if (jQuery('div#reactions').length > 0){// && typeof(reactionsConfig) !== "undefined"){

           var react    = new gigya.services.socialize.UserAction();
           //var assetURL = jQuery('#location').val();

           react.setTitle(jQuery('.post-title').val());
           react.setLinkBack(jQuery('.post-location').val());
           react.setDescription(jQuery('.post-summary').val());

           // Adding a Media
           var mediaReaction = null;
          if (jQuery('#itemPath').length > 0){
					if ( jQuery('#itemPhoto').html() !== ''){
                            mediaReaction = {
                                        type: 'image',
                                        src:  jQuery('#itemPhoto').html(),
                                        href: jQuery('#location').val()
                                    };

                    }
            }
            else if (jQuery('#firstPhotoURL').val()){
                    mediaReaction = {
                        type: 'image',
                        src:  jQuery('#firstPhotoURL').val(),
                        href: jQuery('#location').val()
                    };
           }


           //attach media
           if (mediaReaction){
               react.addMediaItem(mediaReaction);
           }


           var textReactions=[
                {
                    text: '',
                    ID: 'agree',
                    tooltip:'I agree with this!',
                    feedMessage: 'I agree with this from Teleread',
                    headerText: 'You agree with this...',
					iconImgUp: 'http://cdn.gigya.com/gs/i/reactions/icons/Agree_Icon_Up.png',
					iconImgiconImgOver: 'http://cdn.gigya.com/gs/i/reactions/icons/Agree_Icon_Down.png'
                }
                ,{
                    text: '',
                    ID: 'disagree',
                    tooltip:'I disagree with this!',
                    feedMessage: 'I disagree with this from Teleread',
                    headerText:'You disagree with this...',
					iconImgUp: 'http://cdn.gigya.com/gs/i/reactions/icons/Disagree_Icon_Up.png',
					iconImgiconImgOver: 'http://cdn.gigya.com/gs/i/reactions/icons/Disagree_Icon_Down.png'
                }
                ,{
                    text: '',
                    ID: 'important',
                    tooltip:'This is important!',
                    feedMessage: "I read this from Teleread and think it's important",
                    headerText:'You think this is important...',
					iconImgUp: 'http://cdn.gigya.com/gs/i/reactions/icons/Important_Icon_Up.png',
					iconImgiconImgOver: 'http://cdn.gigya.com/gs/i/reactions/icons/Important_Icon_Down.png'
                }
            ];

        

           //update feedMessage
		   /*
           var feedMessage = null;
           for(var i=0; i < textReactions.length; i++){
                 if (typeof (textReactions[i].feedMessage) !== "undefined"){
                     feedMessage = textReactions[i].feedMessage;
                     feedMessage = feedMessage.replace('{PUB}', jQuery('#site-title').val());
                     textReactions[i].feedMessage = feedMessage;
                 }
            }
			*/
            // Define the Reactions Plugin's params object
            var d = new Date();
            var timeparam = d.getTime() + 2592000000;

            var reactionParams ={
                barID:              jQuery('.post-location').val(),//reactionsConfig.barID, //  Identifier of the content to which this reaction refers
                containerID:        'reactions',  // Reactions Plugin DIV Container
                reactions:          textReactions,  // The reaction array
                userAction:         react,  // The UserAction object
                bodyText:           'Share it with your friends:', // optional - text that appears in the Share popup
                showSuccessMessage: 'Reaction Shared Successfully', //optional - success feedback on sharing
                cid:                'blog', //context id
                layout:             'horizontal',
                noButtonBorders:    false,
                showCounts:         'right', //display count or not
                countType:          'number', //type of reaction count
                multipleReactions:  'false',//submit multiple reactions
                cancelReactions:    true, //can cancel his reactions
                context:            'ReactionPlugin', // string to identify the context object
                onSendDone:         reactionCallback,
                onError:            errorCallback,
                showAlwaysShare:    'unchecked',
                autoShareActionID:  'reaction',
                autoShareExpiration:timeparam
            };

            // render top reactions
            reactionParams.onLoad = function(event){
                                            jQuery('div.reactionsTop').css('display','block');
                                            jQuery('div.shareComments').css('display','block');
                                    }
            gigya.services.socialize.showReactionsBarUI(conf,reactionParams);

            //copy previous object and change containerID and onLoad property
            var reactionParamsBottom = jQuery.extend({},reactionParams);
            reactionParamsBottom.containerID = 'reactions-bottom';

            //render bottom reactions
            reactionParamsBottom.onLoad = function(event){
                                            jQuery('div#reactions-bottom').css('display','block');
                                          }
            gigya.services.socialize.showReactionsBarUI(conf,reactionParamsBottom);
       }

       /** Activity Feed Plugin **/
       if (jQuery('#activity-feed-container').length > 0)  {
            var height = 330;
            var width  = 300;

            var activityFeedParams = {
                //General parameters
                containerID:            'activity-feed-container',  // The ID of the <DIV> element on the page in which the Plugin should be displayed.
                width:                  width,  //width in px
                height:                 height, //height in px
                siteName:               'Teleread', //site name
                updateFreq:             10,   //update frequency in seconds
                tabOrder:               'everyone,me,friends', //comma separated list, e.g. "everyone,friends,me",
                initialTab:             'everyone', //set the default tab
                borderColor:            '#aaaaaa',    //hex value, e.g. #ff0000
                separatorColor:         '#000000', //hex value, e.g. #ff0000
                loginUI:                'default', //login Plugin used 'default' or 'custom'
                loginUIConfig:          '<config><body><captions background-color="#52A4DA" color="#FFFFFF"></captions><texts color="#353535"><links color="#0000FF"></links></texts><controls><snbuttons color="#000000"></snbuttons><scrollingarrow color="#BBE4FF"></scrollingarrow></controls><background frame-color="Transparent"></background></body></config>', //UI XML
                friendSelectorUIConfig: '<config><body><texts color="#2B2B2B"></texts><background background-color="Transparent" frame-color="#AAAAAA"></background></body></config>', //UI XML
                invitationText:         'Hi - I just visited this site and thought you would find it interesting: $invitationURL',
                invitationURL:          'Teleread',//jQuery('#site-title').val(),
                cid:                    'activityfeed', //context id to tag data
                context:                'activityFeedPlugin', // string to identify the context object
                onError:                errorCallback,
                onLoad:                 function(event){
                                            jQuery('#activity-feed').css('display','block');

                                            // Adjust for IE
                                            if (jQuery.browser.msie){
                                                jQuery('#activity-feed-container').css('height','355px');
                                            }
                                        }
            };

            gigya.services.socialize.showFeedUI(conf, activityFeedParams);

       }

       //global event handlers
    gigya.services.socialize.addEventHandlers(conf,{onConnectionAdded:update,
                                                    onConnectionRemoved:updateUI,
                                                    onLogin:update,
                                                    onLogout:updateUI
                                                   });

    gigya.services.socialize.getUserInfo(conf,{callback:updateUI});

   }
});
