var welcometext = true;
var showreviews = 3;
var view = 'home';
var page = '';
var oid = '';
var showingusereditor = false;
var showingbusinesseditor = false;
var showingadvertise = false;
var timer;
var fancyvars = {};	

jQuery(document).ready(
	function(){
		
		// Initialization Steps
		$.history.init(function(hash){
			var hashparts = {}, re = /([^&=]+)=([^&]*)/g, m;
			if(hash != "") {
				hash = hash.replace(/^.*#?!/, '');
				while (m = re.exec(hash)) {
					hashparts[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
				}
			}
			handleAjax(hashparts);
		},
		{ unescape: ",/" });

		setupToolTips('#featuredprofile, #review-categories');
		setupSearch('.search');

		// Calculate Sidebar Reviews and Load Them
		showreviews = Math.floor(($('#content').innerHeight() - 230)/129);
		$('.reviews').load('/block.php?b=rblist&npp=' + showreviews);
		
		// Set Profile Links
		$(document).on('click', '.lnk_profile', function(){ $.history.load($(this).attr('href')); return false; });

		// Setup Category Navigation
		$('.category-nav li').click(
			function(){
				if(!$(this).hasClass('selected'))
				{
					var selected = $(this);
					var category = $(this).find('a').attr('rel');
					var url = $(this).find('a').attr('href');
					$.history.load(url);
					$('.category-nav li.selected').removeClass('selected').find('span').remove();
				}
				return false;
			}
		);
		
		/*
					
					if(view != 'home')
					{
						restoreHome();
					}
					if(welcometext)
					{
						$('#welcomehome, .content-hr:eq(0)').hide(800, function(){$(this).remove(); });
						welcometext = false;
					}
					showreviews = 10;
					
					$(this).addClass('wait');
					var selected = $(this);
					var category = $(this).find('a').attr('rel');
					var url = $(this).find('a').attr('href');
					
					
					$('#thirdpos').css('opacity',0).load(
							'/block.php?b=brlist&cat=' + category,
							function(){
								$(selected).removeClass('wait').addClass('selected').html('<span class="selected-arrow"></span>' + $(selected).html());
								$('#featuredprofile .coupon-block').hide(600, function(){
									$(this).remove();
									showreviews = Math.round(($('#content').innerHeight() - 230)/129);
									$('.reviews').load('/block.php?b=rblist&cat=' + category + '&npp=' + showreviews);
								});
								setupToolTips('#catlist');
								setupPager('#thirdpos','/block.php?b=brlist&cat=' + category);
								$('#thirdpos').animate(
									{opacity:1},
									function(){

									}
								);
								showreviews = Math.round(($('#content').innerHeight() - 230)/129);
								$('.reviews').load('/block.php?b=rblist&cat=' + category + '&npp=' + showreviews);
							}
					);
				}
				return false;
			}
		);*/

		// Setup Reviewlist Navigation
		$('.review-categories a').click(
			function(){
				var selected = $(this);
				var category = $(this).attr('href');
				$(this).addClass('wait');
				$('.reviews').load('/block.php?b=rblist&cat=' + category + '&npp=' + showreviews, function(){ $(selected).removeClass('wait'); });
				return false;
			}
		);

		// Setup reviewus links
		$('.reviewus').live('click',
			function(){
				if(!$(this).hasClass('noload'))
					showProfileResults($(this).attr('rel'));
				reviewerhref = $(this).attr('href');
				$.fancybox(
					{
						'href':reviewerhref,
						'type':'ajax',
						'autoSize': true,
						'padding': 0,
						'margin': 0
					}
				);
				return false;
			}
		);

		// Setup Advertise Navigation
		$('.signupnow').click(
			function(){
					var url = $(this).attr('href');
					$.history.load(url);
				return false;
			}
		);
		
		$('.navigation').on('click',
			function(){
				var url = $(this).attr('href');
				$.history.load(url);
				return false;
			}
		);
		
		// Setup Page Specific Stuff
		if(urlParams['cat'])
			setupPager('#thirdpos','/block.php?b=brlist&cat=' + urlParams['cat']);
		
		$('#wrap').delay(1000).animate({'opacity':1},3000);
	}
);

function handleAjax(hashparts){
	checkAuthenticated(hashparts);
	var target1 = '';
	var target2 = '';
	var target3 = '';
			if(hashparts['page'] == 'category' || hashparts['page'] == 'search')
			{
				if(hashparts['pn'])
				{
					//Pager used
					$('#thirdpos').fadeOut(800,
						function()
						{
							var geturl;
							if(hashparts['page'] == 'search')
								geturl = '/block.php?b=brlist&term=' + hashparts['term'] + '&npp=' + hashparts['npp'] + '&pn=' + hashparts['pn'];
							else
								geturl = '/block.php?b=brlist&cat=' + hashparts['cat'] + '&npp=' + hashparts['npp'] + '&pn=' + hashparts['pn'];
							$.ajax({
								url: geturl,
								success: function(data, textStatus, jqXHR){
									$('#thirdpos').html(jqXHR.responseText);
									if ( /pager/.test(jqXHR.responseText))
										setupPager('#thirdpos','/block.php?b=brlist&cat=' + hashparts['cat'] );
									$('#thirdpos').fadeIn(2000);
									$('html,body').animate({scrollTop:$('#thirdpos').offset().top - 50},400);
								}
							});
						}
					);
				}
				else
				{
					
					$('#content').fadeOut(800,
						function()
						{
							$('#firstpos').html('');
							var geturl;
							if(hashparts['page'] == 'search')
								geturl = '/block.php?b=brlist&term=' + hashparts['term'];
							else
								geturl = '/block.php?b=brlist&cat=' + hashparts['cat'];
							if(hashparts['npp'] && hashparts['pn'])
								geturl += '&npp=' + hashparts['npp'] + '&pn=' + hashparts['pn'];
							$.when(
								$.ajax('/block.php?b=featured-listing&cat=' + hashparts['cat'] + '&coupons=0'),
								$.ajax(geturl)
							).then(
								function(a1, a2){
									var jqXHR = a1[2];
									$('#secondpos').html(jqXHR.responseText);
									var jqXHR = a2[2];
									$('#thirdpos').html(jqXHR.responseText);
									$('.newbusiness a').bind('click',function(){ openAddBusiness(hashparts['cat']); return false; });
									if ( /pager/.test(jqXHR.responseText))
										setupPager('#thirdpos','/block.php?b=brlist&cat=' + hashparts['cat']);
									updateSideBar(hashparts['page'], hashparts['page'] == 'category' ? hashparts['cat'] : '');
									$('#content').fadeIn(2000);
								}
							);
						}
					);
				}
				// Do something
				if(hashparts['do'])
				{
					switch(hashparts['do'])
					{
						case 'add':
							openAddBusiness(hashparts['cat']);
					}
				}
				oid = hashparts['cat'];
			}
			else if(hashparts['page'] == 'profile')
			{
				if(hashparts['page'] == page && hashparts['bid'] == oid)
				{
				}
				else
				{
					$('#content').fadeOut(800,
						function()
						{
							$('#firstpos').html('');
							$.when(
								$.ajax('/block.php?b=businessprofile&bid=' + hashparts['bid']),
								$.ajax('/block.php?b=businessrblist&bid=' + hashparts['bid'])
							).then(
								function(a1, a2){
									var jqXHR = a1[2];
									$('#secondpos').html(jqXHR.responseText);
									$('#secondpos .reviewus').bind('click',function(){ openReview(hashparts['bid']); return false; });
									var jqXHR = a2[2];
									$('#thirdpos').html(jqXHR.responseText);
									$('.newreview a').bind('click',function(){ openReview(hashparts['bid']); return false; });
									$('#editbusiness').bind('click',function(){ editorSidebar(hashparts['bid']); return false; });
									if ( /pager/.test(jqXHR.responseText))
										setupPager('#thirdpos','/block.php?b=rblist&bid=' + hashparts['bid']);
									updateSideBar(hashparts['page'], hashparts['bid']);
									$('#content').fadeIn(2000);
								}
							);
						}
					);
				}
				// Do something
				if(hashparts['do'])
				{
					switch(hashparts['do'])
					{
						case 'review':
							openReview(hashparts['bid']);
					}
				}
				oid = hashparts['bid'];
			}
			else if(hashparts['page'] == 'user')
			{
				$('#content').fadeOut(800,
					function()
					{
						$('#firstpos').html('');
						$.when(
							$.ajax('/block.php?b=userprofile&uid=' + hashparts['uid']),
							$.ajax('/block.php?b=userrblist&uid=' + hashparts['uid'])
						).then(
							function(a1, a2){
								var jqXHR = a1[2];
								$('#secondpos').html(jqXHR.responseText);
					//$('#secondpos .reviewus').bind('click',function(){ openReview(hashparts['bid']); return false; });
								var jqXHR = a2[2];
								$('#thirdpos').html(jqXHR.responseText);
					//			if ( /pager/.test(jqXHR.responseText))
					//				setupPager('#thirdpos','/block.php?b=rblist&bid=' + hashparts['bid']);
//TODO load user profile sidebar
								updateSideBar(hashparts['page'], hashparts['uid']);
								$('#content').fadeIn(2000);
							}
						);
					}
				);
			}
			else if(hashparts['page'] == 'static')
			{
					$('#content').fadeOut(800,
						function()
						{
							$('#secondpos').html('');
							$('#thirdpos').html('');
							$.ajax({
								url: '/block.php?b=' + hashparts['content'],
								success: function(data, textStatus, jqXHR){
									$('#firstpos').html(jqXHR.responseText);
									$('#content').fadeIn(2000);
									$('html,body').animate({scrollTop:$('#firstpos').offset().top - 50},400);
								}
							});
						}
					);
			}
			else if(hashparts['page'] == 'advertise')
			{
					var show = 'adtext';
					view = "advertise";
					if(hashparts['pid'])
					{
						show = 'adform';
					}
					$('#content').fadeOut(800,
						function()
						{
							var gourl = '/block.php?b='+show+'&pid='+hashparts['pid'];
							if(hashparts['bid'])
								gourl += '&bid=' + hashparts['bid'];
							$('#secondpos').html('');
							$('#thirdpos').html('');
							$.ajax({
								url: gourl,
								success: function(data, textStatus, jqXHR){
									$('#firstpos').html(jqXHR.responseText);
									$(".accordion").accordion({
										autoHeight: false,
										navigation: true,
										collapsible: true, 
										active: false 											
									});
									$('#content').fadeIn(2000);
									$('html,body').animate({scrollTop:$('#firstpos').offset().top - 50},400);
									if(show == 'adform')
										setupAdForm(hashparts['pid'],hashparts['bid']);
									updateSideBar(hashparts['page'], hashparts['do'], hashparts['bid']);
								}
							});
						}
					);
			}
			else
			{
				$('#content').fadeOut(800,
					function()
					{
						$('#thirdpos').html('');
						$.when(
							$.ajax('/block.php?b=intro'),
							$.ajax('/block.php?b=featured-listing')
						).then(
							function(a1, a2){
								var jqXHR = a1[2];
								$('#firstpos').html(jqXHR.responseText);
								var jqXHR = a2[2];
								$('#secondpos').html(jqXHR.responseText);
								updateSideBar('');
								$('#content').fadeIn(2000);
							}
						);
					}
				);
			}
			page = hashparts['page'];
}

function openAddBusiness(catid)
{
		reviewerhref = "/block.php?b=addbusiness&cat="+catid;
		$.fancybox(
			{
				'href':reviewerhref,
				'type':'ajax',
				'autoSize': true,
				'padding': 0,
				'margin': 0,
				'afterShow':function(){
					$('#addBusinessForm').find('.submit').click(function(){
						
						if($('#addBusinessForm').find('#categoryid').val() == '' || $('#addBusinessForm').find('#businessname').val() == '')
						{
							if($('#addBusinessForm').find('#categoryid').val() == '')
							{
								$('#addBusinessForm').find('#categoryid').after('<div class="error">Select Category</div>');
							}
							if($('#addBusinessForm').find('#businessname').val() == '')
							{
								$('#addBusinessForm').find('#businessname').after('<div class="error">Enter Business Name</div>');
							}
						}
						else
						{
							$.post(
								'/api/companies/create_business.json',
								$('#addBusinessForm').serialize(),
								function(bdata)
								{
									if(bdata.status == '201')
									{
										var businessid = bdata.data.businessid;
										$.post(
											'/api/companies/map_category.json',
											$('#addBusinessForm').serialize()+"&businessid="+businessid,
											function(cdata)
											{
												if(cdata.status == '201')
												{
													$.fancybox.close();
													$.history.load('#!page=profile&bid='+businessid);
												}
											},
											'json'
										);
									}
								},
								'json'
							);
						}
					});
				}
			}
		);
}

function updateSideBar(page, oid, adbid)
{
	var cat = (page == 'categoy' && oid != '') ? oid : '';
	var showuser = (page == 'user' && oid == readCookie('userid')) ? true : false;
	var showbusiness = (page == 'profile' && oid == readCookie('userid')) ? true : false;
	var showadvertise = (page == 'advertise') ? true : false;
	if($('.category-nav li.selected')) $('.category-nav li.selected').removeClass('selected').find('span').remove();
	if(page == 'category' && oid)
		$('.category-nav li').has('a[rel='+oid+']').addClass('selected').prepend('<span class="selected-arrow"></span>');
	showreviews = Math.round(($('#content').innerHeight() - 230)/129);
	
	if(showuser)
	{
		$('#reviews-wrap, #control-wrap, #advertise-wrap').fadeOut(
			200,
			function(){
				showingusereditor = true;
				//$('#control-wrap').load('/block.php?b=usereditor&userid=' + oid,function(){$(this).fadeIn(200)})
				$.ajax({
					url: '/block.php?b=usereditor&userid=' + oid,
					success: function(data, textStatus, jqXHR){
						$('#control-wrap').html(jqXHR.responseText).fadeIn(500);
						if(showingadvertise)
						{
							showingadvertise = false;
							$('#catnav-wrap').fadeIn(500);
						}
						setupUserEditor(oid);
					}
				});
			}
		);
	}
	else if(showbusiness)
	{
		showingbusinesseditor = true;
//TODO
	}
	else if(showadvertise)
	{
		showingadvertise = true;
		var adplansurl = '/block.php?b=adplans';
		if(adbid) adplansurl += '&bid='+adbid;
		$('#reviews-wrap, #control-wrap, #catnav-wrap').fadeOut(
			200,
			function(){
				$.ajax({
					url: adplansurl,
					success: function(data, textStatus, jqXHR){
					$('#advertise-wrap').html(jqXHR.responseText).fadeIn(500)
						if(oid)
						{
		//TODO Highlight selected plan
						}
					}
				});
			}
		);
	}
	else if(showingusereditor || showingbusinesseditor || showingadvertise)
	{
		$('#control-wrap').fadeOut(
			200,
			function(){
				showingusereditor = false;
				showingbusinesseditor = false;
				$.ajax({
					url: '/block.php?b=rblist&cat=' + cat + '&npp=' + showreviews,
					success: function(data, textStatus, jqXHR){
						$('.reviews').html(jqXHR.responseText);
						$('#reviews-wrap').fadeIn(500);
						if(showingadvertise)
						{
							showingadvertise = false;
							$('#catnav-wrap').fadeIn(500);
						}
					}
				});
			}
		);
	}
	else
	{
		$('.reviews').fadeOut(
			200,
			function(){
				//$(this).load('/block.php?b=rblist&cat=' + cat + '&npp=' + showreviews,function(){$(this).fadeIn(200)})
				$.ajax({
					url: '/block.php?b=rblist&cat=' + cat + '&npp=' + showreviews,
					success: function(data, textStatus, jqXHR){
						$('.reviews').html(jqXHR.responseText).fadeIn(500);
					}
				});
			}
		);
	}
}

function restoreHome(){
	view = 'home';
	$('.blockcontainer').animate(
		{opacity:0},
		function(){
			$('#firstpos').html('');
			$('#secondpos').load(
				'/block.php?b=featured-listing&coupons=false',
				function(response)
				{
					$('#secondpos').animate(
						{opacity:1}
					);
				}
			);
			$('#thirdpos').html('');
		}
	);
}

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

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

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

function checkAuthenticated(hashparts)
{
	if(readCookie('userid') && readCookie('sessid'))
	{
		$.get(
			'/api/login/authenticated.json/'+readCookie('sessid'),
			function(data)
			{
				if(data.status == 200)
				{
					clearTimeout(timer);
					createCookie('userid',readCookie('userid'),20160);
					createCookie('sessid',readCookie('sessid'),20160);
					setTimeout('checkAuthenticated()',7210000);
				}
				else
				{
					var oid;
					if(hashparts['cat'])
						oid=hashparts['cat'];
					else if(hashparts['term'])
						oid=hashparts['term'];
					else if(hashparts['bid'])
						oid=hashparts['bid'];
					else if(hashparts['uid'])
						oid=hashparts['uid'];
					if(hashparts['do'])
						oid+='&do='+hashparts['do'];
					eraseCookie('userid');
					eraseCookie('sessid');
					window.location='/signup?redirect='+hashparts['page']+'&oid='+oid;
				}
			},
			'json'
		);
	}
	else
	{
		if($('#userauthenticated').length > 0)
			window.location.reload();	
	}
}

function setupAvatarLoader()
{
	if($('#avatar').length > 0){
		var uploader = new qq.FileUploader({
			element: document.getElementById('avatar'),
			action: '/lib/php/avatar.php',
			params: {},
			multiple: false,
			allowedExtensions: ['jpg', 'jpeg', 'png'],  
			sizeLimit: 0,  
			minSizeLimit: 0,
			debug: false,
			onSubmit: function(id, fileName){
				$('.qq-upload-list li').remove();
			},
			onProgress: function(id, fileName, loaded, total){},
			onComplete: function(id, fileName, responseJSON){
				if(responseJSON.filename)
				{
					$('input[name=avatar]').attr('value','/uploads/avatars/'+responseJSON.filename);
					fancyvars['afterClose'] = function(){
						$('#imgarea img').imgAreaSelect({remove:true});
					}
					fancyvars['afterShow'] = function() { setupImageCrop(); };
					fancyvars['href'] = '/imagecrop.php';
					fancyvars['type'] = 'ajax';
					fancyvars['autosize'] = true;
					fancyvars['padding'] = 18;
					fancyvars['margin'] = 10;
					fancyvars['wrapCSS'] = 'fb_signup';
					$.fancybox.open(fancyvars);
					fancyvars['afterClose'] = '';
				}
			},
			onCancel: function(id, fileName){},
			messages: {
				// error messages, see qq.FileUploaderBasic for content            
			},
			showMessage: function(message){
				alert(message);
			}
		});
	}
}

function setupImageCrop(){
	if($('#imgarea').length > 0)
	{
		$('#imgarea img, #imagetoavatar img').attr('src','/images/image.php?width=300&image='+$('input[name=avatar]').attr('value'));
		$('input[name=is]').val($('input[name=avatar]').attr('value'));
		$('#imgarea img').imgAreaSelect({
        handles: true,
				onSelectChange: imageCropPreview,
        onSelectEnd: imageCropComplete,
				aspectRatio: '1:1',
				x1:0,
				y1:0,
				x2:64,
				y2:64
    });
	 setupSubmit('#imagecropform');
		$('#imagecropform').submit(
			function(){
				$("#imagecropform .submit").hide();
				$.post(
							'/lib/php/crop.php',
							$(this).serialize(),
							function(data, status){
									if(data.status == '200')
									{
										//change avatar images on page
										$('.choose_avatar .icon img, .companyLogo img').attr('src',$('input[name=avatar]').attr('value'));
										$.fancybox.close();
									}
									else
									{
										alert(data.message);
									}
									$("#imagecropform .submit").show();
							},
							'json'
					);
				return false;
			}
		);
		
	}
}

function imageCropComplete(img, selection) {
		$('input[name=x1]').val(selection.x1);
		$('input[name=y1]').val(selection.y1);
		$('input[name=x2]').val(selection.x2);
		$('input[name=y2]').val(selection.y2);
		$('input[name=iw]').val($(img).width());
		$('input[name=ih]').val($(img).height());
}

function imageCropPreview(img, selection) {
		var scaleX = $('#imagetoavatar').width() / (selection.width || 1);
		var scaleY = $('#imagetoavatar').height() / (selection.height || 1);

    $('#imagetoavatar > img').css({
        width: Math.round(scaleX * $('#imgarea img').width()) + 'px',
        height: Math.round(scaleY * $('#imgarea img').height()) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

function setupSubmit(scope)
{
    if(!scope) scope='';
    $(scope + ' .submit')
        .append('<input name="submit" type="submit" class="submitBtn" value="">')
        .hover(function () {
            $(this).find('.submitBtn').stop().animate({
                        opacity : 1
                        }, 500);
          },
          function () {
            $(this).find('.submitBtn').stop().animate({
                        opacity : 0
                        });
          });
}
