/*
 * clip-n-share core
 * 
 * uses - citrix-addthis.js for share dropdown
 */

var clipGlobalData = new Array();
clipGlobalData['count'] = '0';
clipGlobalData['currentClip'] = '';
clipGlobalData['currentCollection'] = '';
clipGlobalData['dialogMode'] = '';
clipGlobalData['delClick'] = '0';


//var CTX_CS_APP = document.location.protocol+"//www.citrix.com/";
if(typeof window.CTX_CS_LAZYINIT != 'undefined' && window.CTX_CS_LAZYINIT==true ){
    CTX_CS_APP = document.location.protocol+"//www.citrix.com/";
}else{
    CTX_CS_APP = document.location.protocol+"//"+document.domain+"/";
}

var MY_CLIPS_URL = CTX_CS_APP+'myclips';
var CITRIX_LOGIN_URL = "https://www.citrix.com/lang/English/publicindex.asp?destURL="+MY_CLIPS_URL;
var CITRIX_LOGOUT_URL = "https://www.citrix.com/English/myCitrix/logout.asp";
var CITRIX_REGISTER_URL = "https://www.citrix.com/English/myCitrix/loginNewUser.asp?destURL="+MY_CLIPS_URL;
var CNS_LEARN_MORE_URL = "http://www.citrix.com/clipandshare_more";

//Google Analytics Global object
var _gaq = _gaq || [];

var clipMenuData = {};
//clip&share configuration 
var clipConfig = {
	
	name:"Clip &amp; Share",
	
	buttonHTML_1:'<div id="cns-global-btn-wrap" class="clipNShareH wide-1"><div><div class="cns-global-count-arrow"><a href="javascript:" id="cns-global-btn">Clip &amp; Share <span class="cns-global-count"></span></a></div></div>',	
	buttonHTML: '<a href="#" id="cns-global-btn">Clip &amp; Share <span class="cns-global-count"></span></a></div></div>',
	
	menuDropdownHTML:	'<div id="cns-menu" class="noclips" >'+
							'<div id="cns-menu-body">'+
								'<div id="cns-menu-head">'+
								'<div class="cns-global-count-arrow">'+
									'<a id="cns-head-btn" href="#">Clip &amp; Share <span class="cns-head-count"></span></a>'+
								'</div>'+
								'</div>'+
								'$CLIPSHARE_BUTTON'+
								'<div id="cns-menu-no-clips">'+
									'<h2>Save, view &amp; share content</h2>'+
									'<p>Collect clips here by clicking the Clip button anywhere you see it.<br/>'+
										'<a href="'+CNS_LEARN_MORE_URL+'">Learn More...</a>'+
									'</p>'+
								'</div>'+
								'<div id="cns-menu-login">'+
								'</div>'+
							'</div>'+
							'<div id="cns-menu-cap"></div>'+
						'</div>',

	menuLoginMessageHTML: 	'<p><a href="'+CITRIX_LOGIN_URL+'">Log in</a> or <a href="'+CITRIX_REGISTER_URL+'">Register</a> to have your clips stored permanently.</p>',
					
	menuWrapperHTML:	'<div id="cns-menu-wrap" class="clipNShareH"></div>',
	
	menuButtonHTML:	'<a href="#" id="clipButton" class="cns-button">Clip Current Page</a>'+
                    '<a class="cns-button share_btn arrowLeft" id="globalShareButton" href="#">Share Current Page</a>',
						
	menuItemsHTML: '<div id="cns-menu-clips">'+
						'<div id="cns-menu-clips-title">Recent Clips</div>'+						
					'</div>',

	cookieDisabledHTML: '<div id="cns-menu" class="noclips cookieDisabled" >'+
							'<div id="cns-menu-body">'+
							
								'<div id="cns-menu-head">'+
								'<div class="cns-global-count-arrow">'+
									'<a id="cns-head-btn" href="#">Clip &amp; Share <span class="cns-head-count"></span></a>'+
								'</div>'+							
								'</div>'+
								'<div id="cns-menu-no-clips">'+	
									'<h2>Please enable your cookies.</h2>'+
									'<p>The clips feature requires you to have "cookies" enabled in your web browser to function properly.</p>'+
									'<p>Once enabled, you will be able to clip pages on Citrix.com, make collections and share them via email and social networks.</p>'+
								'</div>'+								
							'</div>'+
							'<div id="cns-menu-cap"></div>'+
						'</div>',	
						
	globalNavSystemUnavailableHTML:
						'<div id="cns-menu" class="noclips error" >'+
						'<div id="cns-menu-body">'+
							'<div id="cns-menu-head">'+
							'<div class="cns-global-count-arrow">'+
								'<a id="cns-head-btn" href="#">Clip &amp; Share <span class="cns-head-count">X</span></a>'+
							'</div>'+
							'</div>'+

							'<div id="cns-menu-no-clips">'+
								'<h3>We\'re sorry,</h3>'+
								'<p>Clip &amp; Share service is temporarily unavailable. Service will resume shortly.</p>'+
							'</div>'+
						'</div>'+
						'<div id="cns-menu-cap"></div>'+
					'</div>',					
						
	menuConsoleButton: '<a href="'+MY_CLIPS_URL+'" class="" id="cns-console-btn">View and Share My Clips <span class="cns-console-count"></span></a>',

    /* All Dialog Messages */
	//required to be added to all pages
	baseDialogHTML :	'<div id="cns-dialog-container" class="cns-dialog-container">'+	
							'<div class="cns-alert-box" id="cns-alert-box">'+
								'<div class="corner-a"></div>'+
								'<div class="corner-b"></div>'+
								'<div class="shadow-two">'+
									'<div class="shadow-three">'+
										'<div class="cns-alert-box-content">'+
									'</div>'+
								'</div>'+
								'</div>'+
							'</div>'+
						'</div>'+
						'<div style="display: none; height: 772px;" id="cns-ModalBackground" class="cns-ModalBackgroundCommon"></div>',

	
	firstClippedDialogHTML : '<div class="cns-alert-box-content">'+
								 '<h2>You\'ve added your first clip.</h2>'+
								 '<p class="cns-dialog-top">You can access your clips at any time by selecting "My Clips" in the Clip &amp; Share link at the top of the page. <a href="http://www.citrix.com/clipandshare_more">Learn More.</a></p>'+
								 '<p class="cns-login-hint-message"/>'+
								 //'<p class="cns-dialog-bottom-divider"><a href="'+CITRIX_LOGIN_URL+'">Login</a> or <a href="'+CITRIX_REGISTER_URL+'">register</a> to take advantage of the advance features of Clip &amp; Share.</p>'+
								 '<table><tr><td><a id="ok" href="#" class="mediumButton"><span>OK</span></a></td></tr></table>'+
							'</div>',
							 
							
	maxClipLimitDialogHTML :'<div class="cns-alert-box-content">'+
								'<h2>Clip limit reached</h2>'+
								 '<p class="cns-dialog-top">This clip cannot be added because you have reached the maximum number of clips allowed.</p>'+
								 '<p class="cns-login-hint-message"/>'+
								 //'<p class="cns-dialog-bottom-divider">By <a href="'+CITRIX_LOGIN_URL+'">Logging in</a> or <a href="'+CITRIX_REGISTER_URL+'">Registering</a> you can gain access to advanced features, as well as the ability to store more clips.</p>'+
								 '<table><tr><td><a id="ok" href="#" class="mediumButton"><span>OK</span></a></td></tr></table>'+
							'</div>',
	
	deleteClipMessageHTML : 'To delete existing clips, use the <a href="'+MY_CLIPS_URL+'">management console</a>',
	
	maxClipLimitLoginMessageHTML : '<p class="cns-dialog-bottom-divider"><a href="'+CITRIX_LOGIN_URL+'">Log in</a> or <a href="'+CITRIX_REGISTER_URL+'">Register</a> to gain access to advance features, as well as the ability to store more clips.',
	
	maxClipLimitLoggedInUserHTML: '<p style="margin-top:-16px">Please move some clips to another collection to continue to add clips.</p>',
		
	maxCollectionLimitDialogHTML :'<div class="cns-alert-box-content">'+
								'<h2>Collection limit reached</h2>'+
								 '<p class="cns-dialog-top">You have reached the limit of 50 collections.<br/>You must remove a collection before creating a new one.</p>'+
                                 '<table><tr><td><a id="ok" href="#" class="mediumButton"><span>OK</span></a></td></tr></table>'+
							'</div>',

    unavailableDialogHTML : '<div class="cns-alert-box-content">'+
                                 '<h2>We\'re sorry.</h2>'+
                                 '<p class="cns-dialog-top"></p>'+
                                 '<table><tr><td><a id="ok" href="#" class="mediumButton"><span>OK</span></a></td></tr></table>'+
                            '</div>',

    disabledCookieDialogHTML :  '<div class="cns-alert-box-content">'+
								'<h2>Please enable your cookies.</h2>'+
								 '<p class="cns-dialog-top">The clip feature requires you to have "cookies" enabled in your web browser to function properly.</p>'+
                                 '<p class="cns-dialog-top">Once enabled, you will be able to clip pages on Citrix.com, make collections and share them via email and social networks.</p>'+
                            	 '<table><tr><td><a id="ok" href="#" class="mediumButton"><span>OK</span></a></td></tr></table>'+
							'</div>',

    serviceUnavailableMessage: 'Clip &amp; Share service is temporarily unavailable. Service will resume shortly.',

    serviceOutOfSyncDialogMessage : 'We were unable to complete your request. Please refresh the page and try again.'
							
	};

//clipContstants
var clipConstants = {
	NUM_RECENT_CLIPS: 3,
	APP_NAME: "Clip & Share",
	MENU_TIMEOUT: 1500, //3 seconds

	ANONYMOUS_COOKIE_KEY: "CITRIX-CNS-ANON-ID",
	USER_COOKIE_KEY: "CITRIX-CNS-USER",
	SSO_HASH_COOKIE_KEY: "MyCitrixHash",
	SSO_SHADOW_COOKIE_KEY: "MyCitrixShadow",
	SSO_WSAD_COOKIE_KEY: "_wsad_",
	SSO_HASH_COOKIE_ID1: "ID1",
	SSO_HASH_COOKIE_ID2: "ID2",
	
	COOKIE_EXPIRY_DAYS: 30,

	CLIP_DATA_COOKIE_KEY: "CITRIX-CLIP-DATA",

	ANONYMOUS_USER_ID: "ANONYMOUS_USER_ID",

	DEFALUT_COLLECTION_ID: "DEFALUT_COLLECTION",
	DEFAULT_COLLECTION_TITLE: "New Collection",

	SOURCE_CITRIX: "citrix.com",

	RESPONSE_STATUS_OK: "ok",
	RESPONSE_STATUS_FAILURE: "error",

	HTTP_METHOD_GET: 'GET',
	HTTP_METHOD_POST: 'POST',
	HTTP_METHOD_PUT: 'PUT',
	HTTP_METHOD_DELETE: 'DELETE',

	CITRIX_PROXY_URL: CTX_CS_APP +'cns/clip/api/v1.0/',
    
    CNS_SERVICE_URL: CTX_CS_APP +'cns/',
	
	CNS_XDOMAIN_PROXY_URL: 'cns/clip/xdomain/',
	CNS_SERVICE_API_PREFIX: 'api/v1.0/',
	
	ADD_CLIP_URL: 'collections/clips',
	ME_URL: '@me',
	USER_INFO_URL: 'users',
	PREVIEW_PAGE_URL:'/clips',
    MYCLIPS_PAGE_URL:'/myclips',
    MOVE_ANONYMOUS_CLIPS_URL: '@me/anonymous-clips',
		
	//ERROR CODE COMING FROM BACKEND
	ERROR_CLIP_LIMIT_REACHED : 'CLIP_LIMIT_REACHED',
	ERROR_COLLECTION_LIMIT_REACHED:'COLLECTION_LIMIT_REACHED',
    
    LOGOUT_LABEL : 'Logout',
    
    //Constants for Google Analytics
    EVENT_CATEGORY_COLLECTIONS : "Collections",
    EVENT_CATEGORY_CLIPS : "Clips",
    EVENT_CATEGORY_ERRORS : "Errors",
    EVENT_ACTION_COLLECTION : 'New Collection',
    EVENT_ACTION_ADD_CLIP : "Add-Clip",
    EVENT_ACTION_VIEWED_FROM_MOST_RECENT : "Viewed From Most Recent",
    EVENT_ACTION_MAX_COLLECTION_ERROR : "Max Collection",
    EVENT_ACTION_MAX_CLIP_ERROR : "Max Clip",
    EVENT_ACTION_CANNOT_CLIP : "Can't Clip",
    EVENT_ACTION_USER_WRITE_LOCK : "Write Lock"
    
};
 
/**
 * clipcore class.
 * @constructor
 */
function clipCore(){	
	$ = jQuery;
	utils = new clipUtils();
	dialogMgr = new dialogManager();
	clipSelf = this;
}

/**
 * Initialize clip'n'share. This needs to be run on the page
 * using clipCore.js.
 * 
 */
clipCore.prototype.initialize = function() {
	
	utils.common.imagePreLoader(); // preload the menu images.
	//this.createClipLink();
	
	this.createCnsMenu();
	this.initDialog(); //base dialog html has to added to every page
	this.bindEvents();
	addthis.init(); //init addThis service after sharedropdown is populated by the script, have issues otherwise on IEs

    this.updateGlobalNavLoginLink(); //display login/logout link

},

/**
 * changes the login link to logout if the user is logged-in
 * executes only on clip & share pages
 *
 */
clipCore.prototype.updateGlobalNavLoginLink = function(){
    if(utils.common.isPreviewPage() || utils.common.isMyClipsPage()){
        if(utils.cookie.isLoggedIn()){
            var loginLink = $('a','#login');
            loginLink.attr('href',CITRIX_LOGOUT_URL);
            loginLink.html(clipConstants.LOGOUT_LABEL);
        }
    }
},

clipCore.prototype.createCnsMenu = function(){
	
	var isCookieEnabled = utils.cookie.isCookieEnabled();
	var isAnonymous = utils.user.isAnonymous();
	var isAnonymousFirst = utils.user.isAnonymousFirstVisit();
	
	//create the button	
	var searchBox = $('#globalsearch');
	if(searchBox){
		
		//attach the button link and menu html
		var clipLinkWrapper = searchBox.after(clipConfig.buttonHTML_1);				
		var clipMenuWrapper = searchBox.after(clipConfig.menuWrapperHTML);

		//generate menu html
		if(isCookieEnabled){
            if(typeof window.CTX_CNS_PAGECLIP_DISABLE != undefined && window.CTX_CNS_PAGECLIP_DISABLE==true){
                clipConfig.menuDropdownHTML = clipConfig.menuDropdownHTML.replace('$CLIPSHARE_BUTTON','');
            }else{
                clipConfig.menuDropdownHTML = clipConfig.menuDropdownHTML.replace('$CLIPSHARE_BUTTON',clipConfig.menuButtonHTML);
            }

			if(isAnonymous) {				
				$('#cns-menu-wrap').html(clipConfig.menuDropdownHTML);				
				$('#cns-menu-wrap').find('#cns-menu-login').html(clipConfig.menuLoginMessageHTML); //Append the Login message
				
				if(!isAnonymousFirst) {	// Update the clipcount and recent clips, if user is not first time user			
					this.updateMenu.init();
				} else {
					//update the menu with count as 0
					utils.common.updateCounter();
				}			
			} else { // User is Logged In
				$('#cns-menu-wrap').html(clipConfig.menuDropdownHTML);
				this.updateMenu.init();
			}
		}else{
			$('#cns-menu-wrap').html(clipConfig.cookieDisabledHTML);
			//update the menu with count as 0
			utils.common.updateCounter();
		}
	}
	//call share to initialize the share dropdown
	$('.cns-button').share();
},

/**
* appends HTML to body
*/

clipCore.prototype.initDialog = function(){
	$('body').append(clipConfig.baseDialogHTML);
	$(window).resize(function() {
	  if ($('#cns-ModalBackground').css('display') == 'block') {			
			  dialogMgr.resizeDialogBackground();
			  dialogMgr.showDialog();
		  }
	});
},

clipCore.prototype.bindEvents = function(){

	//menu flag for ouside menu click tracker
	var isMenuOn = false;	
	//flag will be set to true if sharedropdown is shown
	var isShareDrpdownOn=false;
	
	//attach click event and show/hide menu
	$(".clipNShareH").click(function(e){

        //if click is on sharebtn then keep the clipNShare dropdown open
        if($(e.target).hasClass('share_btn')){
            return;
        }
        if($(this)[0].id=='cns-global-btn-wrap'){
            utils.common.showMenu();
		}else

		if($(this)[0].id=='cns-menu-wrap'){
            utils.common.hideMenu();
		}		
		isMenuOn = true;
	});
	
	
	//attach mouseEnter on sharedropdown, if the share dropdown is shown then clip dropdown should dont be hidden
	$('.shareDrpDown').bind('mouseenter click',function() {
		isShareDrpdownOn=true;
		if(timer) {
			clearTimeout(timer);
		}
	});
	
	
	//attach body click event , hide menu if its on. 
	$(document).click(function(e) {

        //if click is on sharebtn then keep the clipNShare dropdown open
        if($(e.target).hasClass('share_btn')){
            return;
        }
		if(!isMenuOn){
			if($('#cns-menu-wrap').css('display') == 'block'){				
				utils.common.hideMenu();
			}			
		}else{
			e.stopPropagation();
		}
		isMenuOn = false;
		
	});	
	
	
	//hide menu on mouse out.
	var timer;
	$('#cns-menu-wrap,.shareDrpDown').bind('mouseleave',function(e) {
		if($(this).hasClass('shareDrpDown')){
			isShareDrpdownOn = false;
		}
		//dont hide cns menu if sharedropdown is shown
		if($('#cns-menu-wrap').css('display') == 'block' && !isShareDrpdownOn){		
			timer = setTimeout(function() {
				utils.common.hideMenu();
			}, clipConstants.MENU_TIMEOUT);		
		}		
	});
	
	$('#cns-menu-wrap').bind('mouseenter',function(e) {
		if(timer) {
			clearTimeout(timer);
		}
	});	
	
	//attach a click event to button
	$('#clipButton').click(function(e){
		clipSelf.addPageClip();
		try{
			//this is only in jquery 1.3
			e.stopImmediatePropagation();
		}catch(err){
			e.stopPropagation();
		}
		return false;

	});

}


/**
 * addPageClip - to Clip current page 
 * uses the location.href for url and meta tags for title and description of the page
 *
 */
clipCore.prototype.addPageClip = function(){
	
	var pageUrlRaw = location.href;
	var pageUrlLength = pageUrlRaw.length;
	
	//clip parameters
	if(pageUrlRaw[pageUrlLength-1]=="#"){
		var pageUrl = pageUrlRaw.substring(0, pageUrlLength-1);
	}else{
		var pageUrl = pageUrlRaw;
	}	
	var pageTitle = $('meta[name=title]').attr("content");
	var pageDesc = $('meta[name=description]').attr("content");
	var pageType = 'html';
	
	//Read the html title if the meta title is null
	if(pageTitle == null || pageTitle == ""){
		pageTitle = $('title').html();
	}
	//replace null values with Empty strings	
	if(pageDesc == null) {
		pageDesc = "";
	}
	
	if(utils.common.isPreviewPage()){
		pageType='clip';
	}

	
	//parameters for ajax call
	var url = clipConstants.CITRIX_PROXY_URL + clipConstants.ADD_CLIP_URL;
	var type = clipConstants.HTTP_METHOD_POST;
	var dataType = 'json';
	
	if(utils.common.isThirdPartySite()) {
		url = CTX_CS_APP + clipConstants.CNS_XDOMAIN_PROXY_URL + clipConstants.HTTP_METHOD_POST + "/" + clipConstants.CNS_SERVICE_API_PREFIX + clipConstants.ADD_CLIP_URL ;
		type = clipConstants.HTTP_METHOD_GET;
		dataType = 'jsonp';
	}
	var mimeType = "application/json";
	var paramData = { title: pageTitle, url:pageUrl, description: pageDesc, type:pageType};
	
	
	//callback for add clip service
	var callback = {
        success: function(data, textStatus) {	
			if(data.status == 'ok'){
				clipMenuData = data;
				if(!utils.cookie.isAnonCookieEnabled()  && (typeof data['anonymous-id']!= undefined)){
					var createAnonCookie = utils.cookie.writeCookie(clipConstants.ANONYMOUS_COOKIE_KEY,data['anonymous-id'] ,clipConstants.COOKIE_EXPIRY_DAYS);
					clipSelf.updateMenu.init(); 
				}else{
					clipSelf.updateMenu.init();
				}

				// Data for Google analytics 
				var userid = data['anonymous-id'];
				var isLoggedIn =  utils.cookie.isLoggedIn();
				
				if(isLoggedIn) {
					var userCookie = utils.cookie.getCookie(clipConstants.USER_COOKIE_KEY);
					if(userCookie != undefined && userCookie != "") {
						userid = userCookie;
					}						
				}
				
				//show the first clip added dialog if the existing count is 0
				if(data["is-user-first-clip"]=='true'){
					//Log to Google Analytics - New Default Collection
					_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_COLLECTIONS, clipConstants.EVENT_ACTION_COLLECTION, userid]);
					
					dialogMgr.launchFirstClippedDialog();
				}	
								
				//Log to Google Analytics - Clip-Current-Page
				_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_CLIPS, clipConstants.EVENT_ACTION_ADD_CLIP, pageUrl]);
				
			} else if(data.status == "error") {
				
				//Log to Google Analytics - Can't Clip Error
				_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_ERRORS, clipConstants.EVENT_ACTION_CANNOT_CLIP, pageUrl]);
				
				//for cross domain the proxy wraps errors and sends it as 200
                var response = {responseText:data};
                clipSelf.service.defaultOnAjaxErrorHandler(response,'','');
			}
			return;	
        }
    }

	//add the clip
	this.service.ajax(url, type, mimeType, dataType,  callback, paramData);
	
}

/**
 * Generic addClip can be used for in page clipping 
 *    - updates the header clipNShare button counter and recent clips data
 *    - (optional) callback passed by the caller be invoked on succesful response
 */
 
clipCore.prototype.addClip = function(paramData,addlSuccessCallbk,sourceBtn){
		
	//parameters for ajax call
	var url = clipConstants.CITRIX_PROXY_URL + clipConstants.ADD_CLIP_URL;
	var type = clipConstants.HTTP_METHOD_POST;
	var dataType = 'json';
	
	var mimeType = "application/json";
	
	//callback for add clip service
	var callback = {
        success: function(data, textStatus) {	
            if(data.status == 'ok'){
				clipMenuData = data;
				if(!utils.cookie.isAnonCookieEnabled() && (typeof data['anonymous-id']!= undefined)){					
					var createAnonCookie = utils.cookie.writeCookie(clipConstants.ANONYMOUS_COOKIE_KEY,data['anonymous-id'] ,clipConstants.COOKIE_EXPIRY_DAYS);
					clipSelf.updateMenu.init();
				}else{
					clipSelf.updateMenu.init();
				}
				addlSuccessCallbk(clipMenuData);
				utils.common.stopSpinnerOnSuccess(sourceBtn);
				
				// Data for Google analytics 
				var userid = data['anonymous-id'];
				var isLoggedIn =  utils.cookie.isLoggedIn();
				
				if(isLoggedIn) {
					var userCookie = utils.cookie.getCookie(clipConstants.USER_COOKIE_KEY);
					if(userCookie != undefined && userCookie != "") {
						userid = userCookie;
					}						
				}
				
				//show the first clip added dialog if the existing count is 0
				if(data["is-user-first-clip"]=='true'){
					//Log to Google Analytics - New Default Collection
					_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_COLLECTIONS, clipConstants.EVENT_ACTION_COLLECTION, userid]);
					
					dialogMgr.launchFirstClippedDialog();					
				}
				
				//Log to Google Analytics - Clip-Current-Page
				_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_CLIPS, clipConstants.EVENT_ACTION_ADD_CLIP, paramData['url']]);
				
			} 
			return;	
        },
        failure: function(XMLHttpRequest, textStatus, errorThrown) {
			
			//Log to Google Analytics - Can't Clip Error
        	_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_ERRORS, clipConstants.EVENT_ACTION_CANNOT_CLIP, paramData['url']]);
			
			utils.common.stopSpinnerOnFailure(sourceBtn);
        }
    }

    if(utils.cookie.isCookieEnabled()){
   	
    	//launch loading spinner
        utils.common.startSpinner(sourceBtn);
        //add the clip
        this.service.ajax(url, type, mimeType, dataType,  callback, paramData);
    }else{
        dialogMgr.launchCookieDisabledDialog();
    }
	
}

clipCore.prototype.updateMenu = {
	init: function(){
	
		//parameters for ajax call
		var url = clipConstants.CITRIX_PROXY_URL + clipConstants.ME_URL;
		var type = clipConstants.HTTP_METHOD_GET;
		var dataType = 'json';
			
		if(utils.common.isThirdPartySite()) {
			url = CTX_CS_APP + clipConstants.CNS_XDOMAIN_PROXY_URL + clipConstants.HTTP_METHOD_GET + "/" + clipConstants.CNS_SERVICE_API_PREFIX + clipConstants.ME_URL ;
			type = clipConstants.HTTP_METHOD_GET;
			dataType = 'jsonp';
		}
		
		var mimeType = "application/json";
		
		//request parameters
		var paramData = { 'get-recent-clips': true};
		
		//callback for add clip service
		var callback = {
			success: function(data, textStatus) {	
				if(data.status == 'ok'){
					 
					var isAnonCookieEnabled = utils.cookie.isAnonCookieEnabled();
					var isLoggedIn =  utils.cookie.isLoggedIn();
					
					//Set the UserName Cookie
					if(isLoggedIn && (typeof data['user-id']!= undefined) && data['user-id'] != "") {
						var createUserNameCookie = utils.cookie.writeCookie(clipConstants.USER_COOKIE_KEY,data['user-id']);						
					} else {
						utils.cookie.writeCookie(clipConstants.USER_COOKIE_KEY,"");
					}				
					
					if(isAnonCookieEnabled && isLoggedIn) {
						//Invoke Merge anonymous clips after Get Count so that _wsad_ cookie is set on the browser
						
						
						// Merge the anonymous clips to logged in user and update the count
						if(utils.common.isMyClipsPage()) {
							clipSelf.moveClipsToLoginUser(clipSelf.appendAnonymousCollectionAfterMerge);
						} else {
							clipSelf.moveClipsToLoginUser();
						}

					} else { 

						//update the counter array
						clipGlobalData['count'] = data['total-clips-count'];
						
						//update the menu with latest count
						utils.common.updateCounter();
						
						//hide the no clips message
						if(data['total-clips-count'] >= 1){
						
							//hide the no clip related message
							if($('#cns-menu-no-clips').css('display') == 'block'){
								$('#cns-menu-no-clips').hide();
								$('#cns-menu-clips').show();
							}
							
							if(!$('#cns-menu-clips')[0]){
							
								//remove no clips class
								$('#cns-menu').removeClass('noclips');
								
								//add menu item html structure
								$('#cns-menu-no-clips').before(clipConfig.menuItemsHTML);	
								
							}
							
							
							//add footer console link and count;
							if(!$('#cns-console-btn')[0]){
								$('#cns-menu-cap').html(clipConfig.menuConsoleButton);
								
								//update the menu with latest count
								utils.common.updateCounter();
							}						
							
							
							//clear existing items
							$('#cns-menu-clips a').remove();
							
							
							
							//add latest clips
							var tempArray = data['recent-clips'].reverse();
							for(var i=0; i<tempArray.length; i++){							
								var aTag = document.createElement('a');
								aTag.href = tempArray[i].url;
								
								//to display icon based on the content type
								var cssClass = "cns-menu-clip ";
								switch (tempArray[i].type) {
									 case 'clip': 
												cssClass = cssClass+ "clip-ico-clip";
												break;
									 case 'ppt' : 
												cssClass = cssClass + "clip-ico-ppt";
												break;
									 default :
												cssClass = cssClass + "clip-ico-doc";											
												break;  //will include the html type as well
								}
								aTag.className = cssClass;
								
								if(tempArray[i].title.length >= 70){								
									var tempTitle = tempArray[i].title.substr(0, 70)+'...';
								}else{
									var tempTitle = tempArray[i].title;
								}		
								aTag.innerHTML = unescape(tempTitle);
								
								$('#cns-menu-clips').append(aTag);					
							}
							
							$('#cns-menu-clips').find("a").click(function(){
								_gaq.push(['_trackEvent',clipConstants.EVENT_CATEGORY_CLIPS,clipConstants.EVENT_ACTION_VIEWED_FROM_MOST_RECENT,jQuery(this).attr('href')]);
							})
						}else{
							$('#cns-menu-clips').remove();
							$('#cns-menu-no-clips').show(); // Display No Clip Message
						}
					}
				};
				return;	
			},
			failure: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#cns-menu-wrap').html(clipConfig.globalNavSystemUnavailableHTML);
                clipGlobalData['count'] = 'X';
                //update the menu with latest count
				utils.common.updateCounter();
			}
		}

		//add the clip
		clipSelf.service.ajax(url, type, mimeType, dataType,  callback, paramData,true);
	
	}

}

clipCore.prototype.appendAnonymousCollectionAfterMerge = function(data){
}

clipCore.prototype.moveClipsToLoginUser = function(addlSuccessCallbk) {
	
	var isAnonCookieEnabled = utils.cookie.isAnonCookieEnabled();
	var isLoggedIn =  utils.cookie.isLoggedIn();
	
	if(isAnonCookieEnabled && isLoggedIn) {
		
		//parameters for ajax call
		var url = clipConstants.CITRIX_PROXY_URL + clipConstants.MOVE_ANONYMOUS_CLIPS_URL;
		var type = clipConstants.HTTP_METHOD_PUT;
		var dataType = 'json';
		
		if(utils.common.isThirdPartySite()) {
			url = CTX_CS_APP + clipConstants.CNS_XDOMAIN_PROXY_URL + clipConstants.HTTP_METHOD_PUT + "/" + clipConstants.CNS_SERVICE_API_PREFIX + clipConstants.MOVE_ANONYMOUS_CLIPS_URL ;
			type = clipConstants.HTTP_METHOD_GET;
			dataType = 'jsonp';
		}
		
		var mimeType = "application/json";
		
		
		//callback for move clips from anonymous to login
		var callback = {
	        success: function(data, textStatus) {	
				if(data.status == 'ok'){
					clipSelf.updateMenu.init(); // Update the clipcount
					//Expire the anonymous cookie
					utils.cookie.expireAnonymousCookie();
					
					if(addlSuccessCallbk != undefined) {
						addlSuccessCallbk(data);
					}

				}
				return;	
	        },
	        failure: function(XMLHttpRequest, textStatus, errorThrown) {
	            if(typeof XMLHttpRequest.responseText!= 'undefined' && XMLHttpRequest.responseText!=''){
	                //500 internal server error
	                if(XMLHttpRequest.status!=500){
	                    response = eval( "(" + XMLHttpRequest.responseText + ")" );
	                    errorCode = response['error-msgs'];
	                }
	                
	                if(errorCode == "USER_NOT_FOUND" || errorCode == "COLLECTION_LIMIT_REACHED") {
	                	//Clear the anonymous cookie, as this anonymous collection doesn't exist anymore
						utils.cookie.expireAnonymousCookie();	                	
	                }
	            }
			}
	    }
		
		//add the clip
		this.service.ajax(url, type, mimeType, dataType,  callback);		
	}	
}

/**
 * ajax service for all cross communication
 */
clipCore.prototype.service = {	
	
	//single reusable ajax function.
	ajax: function(url, type, mimeType, dataType,  callback, paramData,supressErorrDialog){
		
		var baseurl = location.href;
		var baseurlSplit = 'http://'+baseurl.split('/')[2]+'/';
		
		if(!utils.common.isAbsoluteUrl(url)) {
			url = baseurlSplit+url;
		}
		
		$.ajax({
			url: url,
			type: type,
			data: paramData,
			dataType: dataType,
			cache:false,
			beforeSend: function(xhr){
				if (xhr.overrideMimeType){
				  xhr.overrideMimeType(mimeType);
				}
				clipSelf.service.onStartAjax();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				if(supressErorrDialog!=true){
                    clipSelf.service.defaultOnAjaxErrorHandler(XMLHttpRequest,textStatus,errorThrown,url,type);
                }
                if(callback.failure){//optional
                    callback.failure(XMLHttpRequest, textStatus, errorThrown);
                }
			},
			success: function(data, textStatus) {				
				callback.success(data, textStatus);
			},
			complete: function (XMLHttpRequest, textStatus) {
				clipSelf.service.onEndAjax();
			}
		});
	
	}, 
	
	onStartAjax: function(){
		// show loader
	},
	
	onEndAjax: function(){
		// hide loader
	},
	
	defaultOnAjaxErrorHandler:function(XMLHttpRequest, textStatus, errorThrown,url,type){
        var response='';
        var errorCode='';
        if(typeof XMLHttpRequest.responseText!= 'undefined' && XMLHttpRequest.responseText!=''){
            //500 internal server error
            if(XMLHttpRequest.status==500){
                errorCode ="API Temporarily Unavailable";
            }else{
                response = eval( "(" + XMLHttpRequest.responseText + ")" );
                if(response['error-msgs'] != undefined && response['error-msgs'].indexOf("USER_IS_WRITE_LOCKED") != -1) {
                	errorCode = "USER_IS_WRITE_LOCKED";
                } else {
                	errorCode = response['error-msgs'];
                }
            }
        }

		var userid = utils.cookie.getCookie(clipConstants.ANONYMOUS_COOKIE_KEY);
		var isLoggedIn =  utils.cookie.isLoggedIn();
		
		if(isLoggedIn) {
			var userCookie = utils.cookie.getCookie(clipConstants.USER_COOKIE_KEY);
			if(userCookie != undefined && userCookie != "") {
				userid = userCookie;
			}						
		}
		
        switch(errorCode){
            // Page is out of sync  (eg. two browser tabs not in sync, logout on a different browser tab)
            case "USER_NOT_AUTHORIZED":
            case "USER_NOT_FOUND":
            case "COLLECTION_NOT_FOUND":
            case "CLIP_NOT_FOUND":
            case "ITEM_NOT_FOUND":
                                 dialogMgr.launchOutOSyncDialog(); break;
            case "USER_IS_WRITE_LOCKED":
            	_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_ERRORS, clipConstants.EVENT_ACTION_USER_WRITE_LOCK, userid]); dialogMgr.launchSystemUnavailableDialog(errorCode,textStatus, errorThrown,url,type);break;		 
            //Clip Limit Reached Dialog
            case "CLIP_LIMIT_REACHED":  _gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_ERRORS, clipConstants.EVENT_ACTION_MAX_CLIP_ERROR, userid]); dialogMgr.launchClipLimitDialog();break;

            //Collection Limit Reached Dialog
            case "COLLECTION_LIMIT_REACHED":_gaq.push(['_trackEvent', clipConstants.EVENT_CATEGORY_ERRORS, clipConstants.EVENT_ACTION_MAX_COLLECTION_ERROR, userid]); dialogMgr.launchCollectionLimitDialog();break;

            //all other errors really
            case "API Temporarily Unavailable":
            default :
                    dialogMgr.launchSystemUnavailableDialog(errorCode,textStatus, errorThrown,url,type);break;
        }	
		
    }
}



/**
 * clipUtils class.
 * @constructor
 */
function clipUtils(){}


/**
 * cookie utils class to create, read, isEnabled, ssoCookie, findCookie
 *
 */
clipUtils.prototype.cookie = {	
	
	//Check if cookies enabled	 		
	isCookieEnabled: function(){
		var cookieEnabled=(navigator.cookieEnabled)? true : false				
		if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
			document.cookie="testctx";
			cookieEnabled=(document.cookie.indexOf("testctx")!=-1)? true : false;
		}
		if (cookieEnabled){
			return true;
		}else{
			return false;
		}		
	},
	
	//check if sso cookies enabled	
	isSSOEnabled: function(){		
		var isMyCitrixHash = this.getCookie(clipConstants.SSO_HASH_COOKIE_KEY);
		var isMyCitrixShadow = this.getCookie(clipConstants.SSO_SHADOW_COOKIE_KEY);				
		if (isMyCitrixHash !=null && isMyCitrixHash != ""){
			return true;
		}
	},
	
	//check if webservice cookie enabled
	isWSEnabled: function(){
		var isWs = this.getCookie(clipConstants.SSO_WSAD_COOKIE_KEY);				
		if (isWs !=null && isWs != ""){
			return true;
		}else{
			return false;
		}
	},
	
	//check if anon cookie enabled
	isAnonCookieEnabled: function(){
		var domainCookies = document.cookie.split(";");
		var cFlag = false;
		for (var i=0;i<domainCookies.length;i++){
			var x = domainCookies[i].substr(0,domainCookies[i].indexOf("="));
			var y = domainCookies[i].substr(domainCookies[i].indexOf("=")+1);
			x = x.replace(/^\s+|\s+$/g,"");
			if(x.length >= clipConstants.ANONYMOUS_COOKIE_KEY.length){
				var z = x.slice(0, clipConstants.ANONYMOUS_COOKIE_KEY.length)
				if(z == clipConstants.ANONYMOUS_COOKIE_KEY){
					cFlag =  true;
				}
			};				
		}
		return cFlag;
	},

	//check if sso cookies enabled	
	// instead of relying on presence of values in browser
	isLoggedIn: function(){		
		var isMyCitrixHash = this.getCookie(clipConstants.SSO_HASH_COOKIE_KEY);
		if (isMyCitrixHash !=null && isMyCitrixHash != ""){
			var cookieValueArray = isMyCitrixHash.split("&");
			
			var ID1 = "";
			var ID2 = "";
			
			for(var i=0;i<cookieValueArray.length;i++) {
				var x = cookieValueArray[i].substr(0,cookieValueArray[i].indexOf("="));
				var y = cookieValueArray[i].substr(cookieValueArray[i].indexOf("=")+1);
				
				if(x == clipConstants.SSO_HASH_COOKIE_ID1) {
					ID1 = y;
				} else if( x == clipConstants.SSO_HASH_COOKIE_ID2 ) {
					ID2 = y;
				}
			}
			
			//Values for ID1 and ID2 are set in MyCitrixHash Cookie when user is logged in
			if( ID1 != null && ID1 != "" && ID2 != null && ID2 != "") {			
				return true;
			} else {
				return false;
			}
		}
	},
	
	//returns value if cookie exist
	getCookie: function(cName){
		var domainCookies = document.cookie.split(";");
		for (var i=0;i<domainCookies.length;i++){
			var x = domainCookies[i].substr(0,domainCookies[i].indexOf("="));
			var y = domainCookies[i].substr(domainCookies[i].indexOf("=")+1);
			x = x.replace(/^\s+|\s+$/g,"");
			if (x == cName){
				return unescape(y);
			}
		}	
	},
	
	//set a cookie
	writeCookie: function(cName,value,exdays){

        if(value && typeof value!=undefined){
            var exdate=new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
            document.cookie=cName + "=" + c_value +"; domain=.citrix.com; path=/";
        }
		return true;
	},
	
	expireAnonymousCookie: function() {
		var anonymousId = this.getCookie(clipConstants.ANONYMOUS_COOKIE_KEY);
		this.writeCookie(clipConstants.ANONYMOUS_COOKIE_KEY, anonymousId, 0);		
	}
}

/**
 * user util class
 *
 */
clipUtils.prototype.user = {
	
	isAnonymous: function(){
		//Anonymous user
		var isLoggedIn = utils.cookie.isLoggedIn();		
		if(isLoggedIn){
			return false;
		}else{
			return true;
		}
	},
	
	isAnonymousFirstVisit: function(){				
		var isAnonCookieEnabled = utils.cookie.isAnonCookieEnabled();		
		if(isAnonCookieEnabled){
			return false;
		}else{
			return true;
		}
	}
	
	
	
}

/**
 * common util class
 *
 */
clipUtils.prototype.common = {
	
	//var self = this;
	// check if the dom tree contains an object
	parentNodeLookup: function(parentName, childObj){
		var testObj = childObj.parentNode;
		var count = 1;
		var tempFlag = true;
		while(testObj.getAttribute('name') != parentName) {		
			testObj = testObj.parentNode;
			count++;
			tempFlag = false;
		}		
		if(tempFlag){
			return true;
		}else{
			return false;
		}
		
	},

	//display the cns menu
	showMenu: function(){		
		//clipSelf.addMenuContent();
		
		$('#cns-global-btn-wrap').hide();
		$('#cns-menu-wrap').show();	
	},
	
	//hide the cns menu
	hideMenu: function(){
		$('#cns-global-btn-wrap').show();
		$('#cns-menu-wrap').hide();	
	},
	
	//preload the images
	imagePreLoader: function(){
	
		// counter
		var i = 0;
		images = new Array('cns/static-assets/images/cns/buttons_sprite.png',
                            'cns/static-assets/images/cns/global_nav_sprite.png',
                            'cns/static-assets/images/cns/tint.png',
                            'cns/static-assets/images/cns/icons_sprite.png',
                            'cns/static-assets/images/cns/common_sprite.png',
                            'cns/static-assets/images/cns/round-box-bk.png',
							'cns/static-assets/images/cns/center_right.png',
							'cns/static-assets/images/cns/bottom_center.png',
							'cns/static-assets/images/cns/top_center.png',
							'cns/static-assets/images/cns/coll-menu-bk-middle.png'
							);

        
		// start preloading
		for(i=0; i<images.length; i++){
			  imageObj = new Image();
              imageObj.src=CTX_CS_APP+images[i];             
		 }
	},

	
	//update the counter on menu
	updateCounter: function(){		
		
		//update the counters
		$('.cns-global-count').html("("+clipGlobalData['count']+")");					
		$('.cns-head-count').html("("+clipGlobalData['count']+")");	
		$('.cns-console-count').html("("+clipGlobalData['count']+")");
		
		//update the css to accomodate numbers
		
		var countLength = ''+clipGlobalData['count'];
		
		if(countLength.length == '1'){
			$('#cns-global-btn-wrap').removeClass().addClass('clipNShareH wide-1');
			//$('#cns-head-btn').removeClass().addClass('wide-2');			
		}
		
		if(countLength.length == '2'){
			$('#cns-global-btn-wrap').removeClass().addClass('clipNShareH wide-2');
			//$('#cns-head-btn').removeClass().addClass('wide-2');			
		}
		
		if(countLength.length == '3'){
			$('#cns-global-btn-wrap').removeClass().addClass('clipNShareH wide-3');
			//$('#cns-head-btn').removeClass().addClass('wide-3');			
		}
		
		/*if($('#cns-menu-wrap').css('display') == 'none'){
			//update collection counte - if exist.
			$(".cns-coll-title span.count").html(" (" + clipGlobalData['count'] + ")");
		}*/
		
	},
	
	isShareDropdownOpen:function(){
		var hoverMenu = $('.'+$.addThis.MENU_CLASS);
		if(hoverMenu.hasClass($.addThis.MENU_CLASS) && hoverMenu.css('display') == 'block'){
			return true;
		}
		return false;
	},
	
	/**
	* Given an element return true if onclick is already registered
	*/
	
	hasOnClick:function(elem){
		if($(elem).data("events")!=undefined && $(elem).data("events").click!=undefined){
			return true;
		}
		return false;
	},

    isMyClipsPage:function(url){
		if(!url){
			url = location.href;
		}
		return url.match(clipConstants.MYCLIPS_PAGE_URL);
	},

	
	/**
	*
	*  url- optional (if not uses the current location ref)
	*/
	isPreviewPage:function(url){
	
		if(!url){
			url = location.href;
		}
		return url.match(clipConstants.PREVIEW_PAGE_URL);
	},
	
	startSpinner:function(sourceBtn){
		//if source-btn is defined that enable the loading icon 
		if(sourceBtn){
			sourceBtn.addClass('loading');
		}
	},
	
	stopSpinnerOnSuccess:function(sourceBtn){
		//remove the loading icon and show clipped icon for a sec on successful addclip action
		if(sourceBtn){
			sourceBtn.removeClass('loading');
			var sourceClass = sourceBtn.attr('class');
			sourceBtn.addClass('clipped');
			setTimeout(function(){sourceBtn.fadeOut('slow', function(){sourceBtn.removeClass('clipped');}).fadeIn('slow');},2000);
		}
	},
	
	stopSpinnerOnFailure:function(sourceBtn){
		//remove the loading icon and show clipped icon for a sec on successful addclip action
		if(sourceBtn){
			sourceBtn.removeClass('loading');
		}
	},

	isAbsoluteUrl:function(url) {
		var strHttp = "http://";
		var strHttps = "https://";
		
		if(url != undefined && url != "") {
			if(url.substring(0, strHttp.length) == strHttp || url.substring(0, strHttps.length) == strHttps) {
				return true;
			}
		}
		return false;
	},
	
	isThirdPartySite:function() {
		if(typeof window.CTX_CS_THIRD_PARTY_SITE != undefined && window.CTX_CS_THIRD_PARTY_SITE==true ){
			return true;
		}
		return false;
	}
}

//Dialog Manager code starts

/**
 *  Bind events for action within the Popular Clipped Items display section
 *
 */
 
 
/**
 * @constructor
 */
function dialogManager(){}


/**
* specific dialog launch functions 
*/


//
dialogManager.prototype.launchSystemUnavailableDialog = function(errorCode, textStatus, errorThrown,url,type){

	$('.cns-alert-box-content').replaceWith(clipConfig.unavailableDialogHTML);

	$('.cns-alert-box-content').find('.cns-dialog-top').html(clipConfig.serviceUnavailableMessage);

	$('#cns-alert-box').css("width",'280px');
	$('#cns-alert-box').css("text-align", "left");

	//show dialog
	this.showDialog();

}

//
dialogManager.prototype.launchOutOSyncDialog = function(){

    $('.cns-alert-box-content').replaceWith(clipConfig.unavailableDialogHTML);

	$('.cns-alert-box-content').find('.cns-dialog-top').html(clipConfig.serviceOutOfSyncDialogMessage); // Append the Login message

	$('#cns-alert-box').css("width",'280px');
	$('#cns-alert-box').css("text-align", "left");

	//show dialog
	this.showDialog();

}


//launch first clipped dialog message
dialogManager.prototype.launchFirstClippedDialog = function(){

	//set the firstclipped message
	$('.cns-alert-box-content').replaceWith(clipConfig.firstClippedDialogHTML);
	if(utils.user.isAnonymous()) {
		$('.cns-alert-box-content').find('.cns-login-hint-message').replaceWith(clipConfig.menuLoginMessageHTML); // Append the Login message
	}
	$('#cns-alert-box').css("width",'280px');
	$('#cns-alert-box').css("text-align", "left");
	
	//show dialog
	this.showDialog();
}

//launch clip limit exceeded dialog
dialogManager.prototype.launchClipLimitDialog = function(){
    
	//set the cliplimit dialog message
	$('.cns-alert-box-content').replaceWith(clipConfig.maxClipLimitDialogHTML);
	if(utils.user.isAnonymous()) {
		$('.cns-alert-box-content').find('.cns-login-hint-message').replaceWith(clipConfig.maxClipLimitLoginMessageHTML); // Append the Login message
	} else {
		$('.cns-alert-box-content').find('.cns-login-hint-message').replaceWith(clipConfig.maxClipLimitLoggedInUserHTML);
	}
	$('#cns-alert-box').css("width",'320px');
	$('#cns-alert-box').css("text-align", "left");
	
	//show dialog
	this.showDialog();
}


//launch collection limit exceeded dialog
dialogManager.prototype.launchCollectionLimitDialog = function(){

	//set the cliplimit dialog message
	$('.cns-alert-box-content').replaceWith(clipConfig.maxCollectionLimitDialogHTML);
	
	$('#cns-alert-box').css("width",'280px');
	$('#cns-alert-box').css("text-align", "left");

	//show dialog
	this.showDialog();
}


//launch clip limit exceeded dialog
dialogManager.prototype.launchCookieDisabledDialog = function(){

	//set the cliplimit dialog message
	$('.cns-alert-box-content').replaceWith(clipConfig.disabledCookieDialogHTML);
	$('#cns-alert-box').css("width",'280px');
	$('#cns-alert-box').css("text-align", "left");

	//show dialog
	this.showDialog();
}

//resizes the modalbackground based on the screen height/width
// should be called during resize and showDialog
dialogManager.prototype.resizeDialogBackground = function(){
	var mbg = $('#cns-ModalBackground');
	mbg.css( {       
		'width': $(window.document).width() + 'px',
		'height': ($(window.document).height() + 300) + 'px'
	});
}

/**
 *  common base dialog functions
 */
dialogManager.prototype.bindEvents = function(){

	//ok button on dialog
	$('.cns-alert-box-content a#ok').click(function(e){		
		//close the dialog
		dialogMgr.hideDialog();
		
	});
}


dialogManager.prototype.showDialog  = function(){

	var div = $("#cns-dialog-container");
	var mbg = $("#cns-ModalBackground");
	
	this.resizeDialogBackground(); //the height of the page could have changed
	 
	mbg.css("display", "block");
	div.css("display","block");
	
	if ( $.browser.msie && $.browser.version == '7.0' ) {
		$('#footerWrapper').css("display", "none");
		mbg.removeClass("cns-ModalBackgroundCommon").addClass('cns-ModalBackgroundIe7');
		$('#cns-console-container').addClass('cnsConsoleIe7');
	}		
	
	//var obj = $("#divID");
	var halfsc = $(window).height()/2;
	var halfh = $('#cns-alert-box').height(); 	
	//var halfh = 90; 	
	
	var halfscrn = $(window).width()/2;
	var halfobj = $('#cns-alert-box').width()/2;
	//var halfobj = 90; 	

	var goLeft =  halfscrn - halfobj ;
	var goTop = halfsc - halfh;
	
	div.css("top", goTop);
	div.css("left", goLeft);
	
	this.bindEvents();
	
	return this;
}	
//reset the dialog
dialogManager.prototype.hideDialog =  function(){
	var mbg = $("#cns-ModalBackground");
	var dwrap = $("#cns-dialog-container");
	
	mbg.css("display", "none");
	dwrap.css("display", "none");
	
	if ( $.browser.msie && $.browser.version == '7.0' ) {
		$('#footerWrapper').css("display", "block");
	
		mbg.addClass("cns-ModalBackgroundCommon").removeClass('cns-ModalBackgroundIe7');
		$('#cns-console-container').removeClass('cnsConsoleIe7');
	
	}
	
	clipGlobalData['dialogMode'] = '';
}
//Dialog Manager code ends


/**
 * share plugin
 *
 * This is javascript file for the implementation of share menu using addThis plug-in.
 */
var addthis_config =
{
		"data_track_clickback":true
};

(function($){

    $.addThis = {
        TOGGLER_CLASS: "share_btn",
        MENU_CLASS: "shareDrpDown",
		MENU_HIDE_TIMEOUT:1400,
        jclass: function(str) {
            return [".", str].join("");
        }
    }

    /* This are all local variables that get enclosed into the functions that
     * use them bellow. They are shortcuts to avoid bigger scope jumps */
    var getClass = $.addThis.jclass,
        TOGGLER_CLASS = $.addThis.TOGGLER_CLASS,
        MENU_CLASS = $.addThis.MENU_CLASS;
		SHAREMENU_HIDE_TIMEOUT=$.addThis.MENU_HIDE_TIMEOUT;

    $.fn.share = function(beforeShow, afterShow){

		if (!$(getClass(MENU_CLASS)).size()) {

            $(document.body).append([
                '<div class="',MENU_CLASS,'">',
                    '<div class="shareTopArrow"></div>',
                    '<div class="shareTopRight">',
                        '<div class="shareTopLeft">',
                            '<div class="shareTopCenter"></div>',
                        '</div>',
                    '</div>',
                    '<div class="shareCenterRight">',
                        '<div class="shareCenterLeft clearfix">',
                            '<ul class="share">',
                                '<li><a class="addthis_button_email"><span class="email">Email</span></a></li>',
                                '<li><a class="addthis_button_twitter"><span class="twitter">Twitter</span></a></li>',
                                '<li><a class="addthis_button_facebook"><span class="facebook">Facebook</span></a></li>',
                                '<li><a class="addthis_button_linkedin"><span class="in">LinkedIn</span></a></li>',
                                '<li><a class="addthis_button_delicious"><span class="del">Delicious</span></a></li>',
                                '<li><a class="addthis_button_digg"><span class="digg">Digg</span></a></li>',
                                '<li class="more"><a class="addthis_button_expanded"><span>More Destinations</span></a></li>',
                            '</ul>',
                        '</div>',
                    '</div>',
                    '<div class="shareBottomRight">',
                        '<div class="shareBottomLeft">',
                            '<div class="shareBottomCenter"></div>',
                        '</div>',
                    '</div>',
               '</div>'
            ].join(""));
        }

        var hideMenu = function() {

            var hoverMenu = $(getClass(MENU_CLASS)),
                customBtn = $([getClass(TOGGLER_CLASS),'.active'].join(""));

		    if (!customBtn.data('in') && !hoverMenu.data('in') && !hoverMenu.data('hidden')) {
            	//If mouse is not on Share link and Share menu, then hide Share menu
                customBtn.removeClass('active');
                hoverMenu.fadeOut('fast').data('hidden', true);
            }
        };

        /* This selector only initialises buttons that haven't been
         * initialised. Initialised buttons have class "addthis-init" */
		$([
            getClass(TOGGLER_CLASS), ':not(addthis-init), ',
            getClass(MENU_CLASS), ':not(addthis-init)'
        ].join(""))
            .addClass("addthis-init")
            .bind('mouseenter',function() {
				var jThis = $(this);
				if (jThis.hasClass(MENU_CLASS)){
	
				    jThis.addClass('active').data('in', true);
				    jThis.fadeIn('fast').data('hidden', false);
				}
            }).bind('mouseleave',function() {
				$(this).data('in', false);
				var timeout=SHAREMENU_HIDE_TIMEOUT;
				if($(getClass(MENU_CLASS)).data('closeNow')){
					timeout=5;
				}
				setTimeout(hideMenu,timeout);

            }).click(function(e){
				var jThis = $(this),
                hoverMenu = $(getClass(MENU_CLASS)),
                position;

			    jThis.addClass('active').data('in', true);
	            hoverMenu.fadeIn('fast').data('hidden', false);
	
	            if (jThis.hasClass(TOGGLER_CLASS)){
					position = jThis.offset();
	
	                try {
	                    var url = jThis.find(".urlToShare").text();
	                    if(url != undefined && url != null && url != "") {
	                    	window.addthis.update('share', 'url', url);
	                    } else {
	                    	//By Default share the page URL
	                    	window.addthis.update('share', 'url', window.location.href);
	                    }
	                    var title = jThis.find(".titleToShare").text();
	
	                    if(title != undefined && title != null && title != "") {
	                    	window.addthis.update('share', 'title', title);
	                    } else {
	                    	//By Default share the page URL
	                    	window.addthis.update('share', 'title', document.title);
	                    }

                    }
                    catch(error) {
                    	//Log the error in console.
                    	//console.log(error);
                    }

                }

				if (position) {
					//if arrowLeft class is provided the share button then addThis dropdown will be displayed next to the share button
					//with arrow pointing to the left
					if(jThis.hasClass("arrowLeft")){
						$(getClass(MENU_CLASS)).find(".shareTopArrow").addClass("shareLeftArrow").removeClass('shareTopArrow');;
					}else if($(getClass(MENU_CLASS)).find(".shareLeftArrow").length>0){
						$(getClass(MENU_CLASS)).find(".shareLeftArrow").addClass("shareTopArrow").removeClass('shareLeftArrow');;
					}
	
					//if the share button has closeNow class then addThis dropdown will be closed instantly
					if(jThis.hasClass("closeNow")){
						hoverMenu.data('closeNow', true);
					}else{
						hoverMenu.data('closeNow', false);
					}
	
					beforeShow && beforeShow(jThis, hoverMenu);
						var hoverMenuCss;
						if(jThis.hasClass("arrowLeft")){ //eg global share button has arrow left
						    hoverMenuCss = {top:position.top,left: (position.left+165+17)}; 
							//165 is the width the of the share button, dynamically computing isnt working on IE9 on random pages
						}else{
							// 9 is the tips height
							// 64 is half of the width of the menu
						    // 22 is half of the width of the share label and icon together
						    // calculate those values might be a good idea at some point
							hoverMenuCss = {top: (position.top + jThis.height() + 9),left: (position.left - 64 + 22)};
						}
					hoverMenu.css(hoverMenuCss);
	                afterShow && afterShow(jThis, hoverMenu);
	            }
				
				try{
					//this is only in jquery 1.3
					e.stopImmediatePropagation();
				}catch(err){
					e.stopPropagation();
				}

				return false;
			});

			/*$('[class*=addthis_button_]').click(function(){
				$(this).data('in', false);
				hideMenu();
			});*/

			$(document).click(function(e) {
				$(this).data('in', false);
				hideMenu();
			});
	}

})(jQuery);

/** end of share plugin **/

/**
 * set a flag based on the location.href to disable pageclip
 */
(function(){
    //disable clipNshare button for myclips page and any page on citrix.com required authentication
    var currentPageUrl = location.href;
	var myCitrixPageUrl = '/mycitrix/';
    if(currentPageUrl.match(clipConstants.MYCLIPS_PAGE_URL) || currentPageUrl.toLowerCase().match(myCitrixPageUrl.toLowerCase())){
        window.CTX_CNS_PAGECLIP_DISABLE=true;
    }
})();


jQuery.noConflict(); // Relinquish jQuery's control of the $ variable

/**
 * Init onReady only if lazyInit global flag is not set
 */
(function(){
    if(typeof window.CTX_CS_LAZYINIT == 'undefined' || window.CTX_CS_LAZYINIT==false){
         function _initClipNShare(){
            if(!clipConstants.INITIALIZED && jQuery('#cns-global-btn-wrap').length==0){
                var clips = new clipCore();
                clips.initialize();
                clipConstants.INITIALIZED=true;
            }
        }

        jQuery(document).ready(_initClipNShare);
        //workaround backup if jquery ready didnt work for some reason
        if (window.attachEvent) {
            window.attachEvent('onload', _initClipNShare);
         }
          else{
            window.addEventListener('load', _initClipNShare, false);
         }
}
})();
