if(!aetn) {
	//init aetn namespace
	var aetn={}; 
}

if(!aetn.mylifetime) {
	//init mylifetime namespace
	aetn.mylifetime={}; 
}

if(!aetn.mylifetime.atl) {
	//init atl namespace
	aetn.mylifetime.atl={}; 
}

aetn.mylifetime.atl.page = function() {
	var pub = {}; //public
	var priv = {}; //private
	
	pub.setSection = function(sectionType) {
		priv.sectionType = sectionType;
	};
	
	pub.getSection = function() {
		return priv.sectionType;
	};
	
	return pub;
}();

aetn.mylifetime.atl.photoBrowser = function() {
	var pub = {}; //public
	var priv = {}; //private
	
	priv.vote_history = {}; //vote history array array
	
	priv.addToVoteHistory = function(nid, value) {
		priv.vote_history[nid] = value;
	};
	
	pub.getVoteHistoryForNid = function(nid) {
		if (priv.vote_history[nid] != undefined) {
			return priv.vote_history[nid];
		} else {
			return false;
		}
	};
	
	pub.adjustVotesForUser = function(nid) {
		
		if (nid == undefined) {
			return;
		}
		
		var photo_vote = pub.getVoteHistoryForNid(nid);
		
		if (photo_vote == false) {
			//user hasn't voted, no need to adjust
			return;
		} else if (photo_vote != 'love' && photo_vote != 'hate') {
			//invalid vote
			return;
		}
		
		
		var love_text = $('#photo_rating_loved').css('width');
		var love_rate_text = love_text.replace("%", "");
	    var love_percent = parseInt(love_rate_text);

		var hate_text = $('#photo_rating_hated').css('width');
		var hate_rate_text = hate_text.replace("%", "");
	    var hate_percent = parseInt(hate_rate_text);

	    var total_text = $('#photo_rating_total span').html();
	    var total_votes = parseInt(total_text);

		if (love_percent !=0 ) {
			love_vote = (love_percent/100)*total_votes;
	    } else {
			love_vote = 0;
	    }
		
	    if (hate_percent != 0) {
			hate_vote = (hate_percent/100)*total_votes;
		} else {
			hate_vote = 0;
		}
	    
	    //adjust for user's vote record in-memory
	    if(photo_vote == 'love'){
	    	love_vote = love_vote + 1;	  
		} else if(photo_vote == 'hate') {
			hate_vote = hate_vote+1;		
		}

	    //increment total votes
		++total_votes;

		//calculate new values
		var loved =  Math.round(parseFloat((love_vote / total_votes ) * 100));
		var hated =  Math.round(parseFloat((hate_vote / total_votes ) * 100));

		//convert to strings
        var loved_string = loved.toString();
        var hated_string = hated.toString();
        var total_vote_text = total_votes.toString();
        
        //set html values
		$('#photo_rating_total span').html(total_vote_text);
		$('#photo_rating_loved_percent span').html(loved_string);
		$('#photo_rating_hated_percent span').html(hated_string);

		$('#photo_rating_loved').css('width',loved_string+'%');
		$('#photo_rating_hated').css('width',hated_string+'%');
		return;
	};
	
	pub.addLoadingIndicator = function(item_dom) {
		$(item_dom).css('margin', '50px 0 0');
		$(item_dom).css('text-align', 'center');
		$(item_dom).html("<img src='/all-the-looks/sites/mylifetime.com.all-the-looks/themes/allthelooks/images/loading_indicators/19-0.gif'>");
	};
	
	pub.ratePicture = function(nid, vote) {
		
		//add to local history
		priv.addToVoteHistory(nid, vote);
		
		var sectionType = aetn.mylifetime.atl.page.getSection();
		
		if (!sectionType) {
			sectionType = 'search';
		}
		
		if (sectionType == 'look-book') { 
		    var destination = $('#allthelooks-rating-vote-form #edit-destination').val();
		    loadLookbookImage(destination);
		} else {
			if (parseInt(currentPage)+2>totalPages) {
		        loadSearchImage(0);
		    } else {
		        loadSearchImage(parseInt(currentPage)+1);
		    }
		}
		
		$.ajax({
				type: "POST",
				url: "/all-the-looks/services/json",
				data: "method=votingapi.setVote&type=atl_ratePicture&content_type=node&content_id=" + nid + "&value_type=percent&tag=" + vote, 
				success: function(data) {
					//show popup and update the points, only if the cookie exist
					if (data['#data'].atl_reward_pt==true) {
				      reward_popup_search_vote('1');
				      update_reward_points();
				    }
				},
				async: true,
				dataType: "json"
		});
	};
	
	return pub;
}();

$(document).ready(function() {

  $('#my-lookbooks-menu.auth_user').hover(
    function() { $('ul', this).css('display', 'block'); },
    function() { $('ul', this).css('display', 'none'); }
  );
  var page_url = window.location;
  var url_parts = page_url.toString().split('/');
  if (url_parts[4] != '' && url_parts[6] != ''){
    $("#edit-pathauto-perform-alias").attr("checked", false);
  }

	jQuery.fn.center = function() {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
	}
});

/**
 * Fix flickering background images in IE. thanks Ted!
 */
Drupal.behaviors.fixIEFlickr = function() {
  if (jQuery.browser.msie) {
    try {
      document.execCommand('BackgroundImageCache', false, true);
    } catch(err) {}
  }
};


function validate_lookbook_form(value_str) {
	var pairs = value_str.split('&');
	var parsed_params = {};
	//var bad =/[^\w\d\s\'\!\-\*\\?]+/; 
	var bad =/[^\w\d\s\'\!\-\\?]+/; 
	//var bad2 =/^[\'\?\!]+$/;
	
	for (i=0; i<pairs.length; i++) {
		var params = pairs[i].split('=');
		parsed_params[urldecode(params[0])] = params[1];
	}
	
	//only need to check a couple of values, no need to loop thru all
	if (parsed_params['title'] == "") { 
		return { 'status':false, 'message':'Please create a title.' }; 
	}
	//test for alpha-nums, ! ? or ' only
	if (bad.test(urldecode(parsed_params['title'])) == true) {
		return { 'status':false, 'message':'Only Alpha-numeric characters, exclamation mark, question mark and apostrophe are allowed.' }; 
	}
	//don't allow them to make a title with only ?!' chars
	/*if (bad2.test(urldecode(parsed_params['title'])) == true) {
		return { 'status':false, 'message':'Please use alpha-numeric characters in your title.' }; 
	}*/
	if (parsed_params['field_public[\'value\']'] == "") { 
		return { 'status':false, 'message':'Please select Public or Private option.' }; 
	}
	
	return { 'status':true };
}

function save_lookbook_data(mode) {
	if (mode != 'rename' && mode != 'create' && mode != 'same-rename') {
		return;
	}

	var form_id = (mode == 'rename' || mode == 'same-rename') ? '#edit-this-lookbook-form' : '#add-lookbook-form';
	var url = '/lookbook/js/'+mode+'-lookbook';
	var value_str = $('#node-form').serialize();
	
	var validation = validate_lookbook_form(value_str);
	
	if (!validation['status']) {
		alert(validation['message']);
		return false;
	}
	else {
		if (mode == 'rename' || mode == 'same-rename') {
			value_str += '&step=2';
		}
		
		if (mode != 'create') {
			if (typeof Drupal.settings.atl != 'undefined') {
				if (typeof Drupal.settings.atl.lookbook_nid != 'undefined') {
				 	url += '/'+Drupal.settings.atl.lookbook_nid;
				}
				if (typeof Drupal.settings.atl.photo_nid != 'undefined') {
					url += '/'+Drupal.settings.atl.photo_nid;
				}
			}
		}
		
		//all the looks prefix
		if (prefix_check()) {
			url = prefix_check() + url;
		}
    //Dart Tag Implementation - for create lookbook -mvijay
    var tag_url = allthelooks_get_spotlightTag('create_lookbook');
    $.get(tag_url);

		$.ajax({
			'type': 'GET',
			'data': value_str,
			'url' : url,
			'success' : function(response) {
				if (mode != 'same-rename') {
				//alert('success');
					if (response == 1) {
						$(form_id+' .form-middle').css('height','auto');
						$(form_id+' .form-display').fadeOut('slow',
							function() {
								$(form_id+' .form-thanks').fadeIn('slow');
							}
						);
						$('.lookbook-list .form-radio').attr('checked', false);
					}
					else if (response == 0) {
						window.location.reload(true);
					}
					else {
						alert('form submission error');
					}

					return false;
				}
				else {
					window.location = response;
				}
			}
		});
	}
}

function is_numeric(mixed_var) {
	// Returns true if value is a number or a numeric string 
	// version: 908.406
	// discuss at: http://phpjs.org/functions/is_numeric
	if (mixed_var === '') {
		return false;
	}

	return !isNaN(mixed_var * 1);
}

function urldecode(str) {
    // Decodes URL-encoded string  
    // 
    // version: 908.1617
    // discuss at: http://phpjs.org/functions/urldecode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +   improved by: Orlando
    // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';

    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}

Drupal.behaviors.lookbookCreate = function(context) {	
	//create lookbook header button
	$('.hdr-btn-createlookbook a', context).click(function() {
		$('.form-createlookbook').show();
		$('#add-photo-form').hide();
		$('#add-lookbook-form .form-middle').css('height','270px');
		$('#add-lookbook-form').center();
		
		//clear the fields if they are set
		$('#edit-title').val('');
		$('#edit-body').val('');
		
		$('#add-lookbook-form').show();
		$('#add-lookbook-form .form-display').show();
		
		return false;
	});
}

Drupal.behaviors.lookbookCreateSubmit = function(context) {
	$("#add-lookbook-form .edit-form-save", context).click(function() {
		save_lookbook_data('create');
		return false;
	});
}

Drupal.behaviors.lookbookCreateCancel = function() {
	$("#edit-cancel").click(function() {
		$('#edit-this-lookbook-form .form-display').hide();
		$('#edit-this-lookbook-form').hide();
		$('#add-lookbook-form').hide();
		$('#add-lookbook-form .form-display').hide();
		return false;
	});
}

function allthelooks_validateMultiEmail(value){ 
  var emails = value.split( new RegExp( "\\s*,\\s*", "gi" ) ); 
  valid = true; 
  for(var i in emails) { 
    value = emails[i]; 
    valid=valid && allthelooks_isValidEmailAddress(value); 
  }
  return valid; 
}

function allthelooks_isValidEmailAddress(emailAddress) {
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
}

function reward_popup_content(val, top_pos, left_pos){
  var popup_top = ($(window).height() - $('#rwd_point_popup_id').height() ) / 2+$(window).scrollTop() + "px";
  var popup_left = ( $(window).width() - $('#rwd_point_popup_id').width() ) / 2+$(window).scrollLeft() + "px";
  if(top_pos != undefined){
    popup_top = top_pos;
  }
  if(left_pos != undefined){
    popup_left = left_pos;
  }
  $('#rwd_point_popup_id').css("position","absolute");
  $('#rwd_point_popup_id').css("top", popup_top);
  $('#rwd_point_popup_id').css("left", popup_left);
  $('#rwd_point_popup_id span').html(val);
  $('#rwd_point_popup_id').show();
  $('#rwd_point_popup_id').fadeOut(5000);
}
function reward_popup_content_with_link(val, class_name){
  var class_check = '.' + class_name;
  if($(class_check).hasClass('showed_popup')){
  }else{
    $(class_check).addClass('showed_popup');
    //reward_popup_content(val);
    var div_pos = $('.search_photo_scollfer').position();
    var top_pos =  div_pos.top + $('.search_photo_scollfer').height() + 15 + "px";
    var left_pos = ($('.search_photo_scollfer').width() / 2) - $('#rwd_point_popup_id').width() + 10 + div_pos.left + "px";
    update_reward_points();
    reward_popup_content(val, top_pos, left_pos);
  }
}
function reward_popup_search_vote(val){
    var div_pos = $('.search_photo_scollfer').position();
    var top_pos =  div_pos.top + $('.search_photo_scollfer').height() + 15 + "px";
    var left_pos = ($('.search_photo_scollfer').width() / 2) - $('#rwd_point_popup_id').width() + 10 + div_pos.left + "px";
    update_reward_points();
    reward_popup_content(val, top_pos, left_pos);
}

Drupal.behaviors.shareButtonShowPopup = function() {
var share_points_awarded = 0;
  $('.ext_share_icons div a').click(function(){
    if(share_points_awarded == 0 ){
      if($('.reward-user-points').html() != '' && $('.reward-user-points').html() != undefined){
        share_points_awarded = 1;
        var a_class = jQuery.trim($(this).attr('class'));
        a_class = a_class.replace(/ /g, '.');	
	
        var atlreward = '/all-the-looks/allthelooks_reward/share_points'
        $.ajax({
          type: "POST",
          url: atlreward,
          beforeSend: function(request) {
            request.setRequestHeader("Connection", "close");
            request.setRequestHeader("Timeout", 300);
          },
          success: function(html) {
            update_reward_points();
            if(html == '1'){
	        reward_popup_content_with_link(5, a_class);
            }
          }
     });      
   }
  }

 });
}

function strip_base_path(url){
  var return_path =  (url != undefined) ? url : document.location.href;
  return_path = return_path.replace(/all-the-looks\//i, "");
  return return_path.toString();
}

/**
* updates the header point strip
*
*/
function update_reward_points() {
  var url = '/lookbook/js/update_head_points';
  //all the looks prefix
  if (prefix_check()) {
    url = prefix_check() + url;
  }
  $.ajax({
    'type'		: 'GET',
    'url' 		: url,
    'success' : function(response) {
        if(response != '') {
          $('.header_buttons .reward-user-points .points').html(response);
        }
      }
  });
}

function initialize_comment_scroll_link(){
	if ($('.comments-wrapper-header').length > 0) {
  	$('.comments-wrapper-header').localScroll();
	}
}

$(document).ready(function(){
  initialize_comment_scroll_link();
});

Drupal.behaviors.spotlightTag  = function() {
  //$(".view-lookbooks.view-display-id-page_4 .rating-btn-container input[@type=submit]").click(function(){
  $(".view-lookbooks.view-display-id-page_4 .rating-btn-container .form-submit").click(function(){
   var tag_url = allthelooks_get_spotlightTag('rate_lookbook');
    $.get(tag_url);
    return true;
  });
}

function allthelooks_get_spotlightTag(action){
  var axel = Math.random()+"";
  var a = axel * 10000000000000;
  var cat = '';
  if (action != ''){
    if(action == 'rate_lookbook'){
      cat = 'ratin974';
    }else if(action == 'create_lookbook'){
      cat = 'creat365';
    }
    var tag_url = 'http://fls.doubleclick.net/activityi;src=2540827;type=allth047;cat=' + cat + ';ord='+ a + '?';
    return tag_url;
  }
  
}

function atl_sendto_friend_submit(target, data) {	
	if(data.urlpass.et_data.status=='unsubscribed') {
		var optedOut = data.urlpass.et_data.failed.join(', ');
		if(data.urlpass.et_data.success.length>0) {
			var success = data.urlpass.et_data.success.join(', ');
			alert('Error: ' + optedOut + ' has opted out from All The Looks Send to Friend requests. ' + success + ' have successfully been sent.');
		} else {
			alert('Error: ' + optedOut + ' has opted out from All The Looks Send to Friend requests.');
		}
	} else {
		var success = data.urlpass.et_data.success.join(', ');
		alert('Email sent to ' + success + '!');
	}
}

var searchPath = '';

function js_search(val){
	if(val=='celebrity'){
		document.getElementById('all').style.display='none';
		document.getElementById('designer').style.display='none';
		document.getElementById('celebrity').style.display='block';
    }
	if(val=='designer'){
		document.getElementById('celebrity').style.display='none';
		document.getElementById('all').style.display='none';
		document.getElementById('designer').style.display='block';
    }
	if(val=='all'){
		document.getElementById('celebrity').style.display='none';
		document.getElementById('designer').style.display='none';
		document.getElementById('all').style.display='block';
    }
}
