// social
function shareFB(title,desc,image) {
    t=encodeURIComponent(title);
    d=encodeURIComponent(desc);
    // u=encodeURIComponent(url);
    i=encodeURIComponent(image);
    share_url='http://www.facebook.com/sharer.php';
    share_url+='?s=100&p[title]='+t+'&p[summary]='+d+'&p[url]='+document.location.href;
    share_url+='&p[images][0]='+i;
    share_url+='&t='+t+'&e='+d;
    return share_url;
}

function shareVK(title,desc,image) {
    t=encodeURIComponent(title);
    d=encodeURIComponent(desc);
    // u=encodeURIComponent(url);
    i=encodeURIComponent(image);
    share_url='http://vkontakte.ru/share.php';
    share_url+='?title='+t+'&description='+d+'&url='+document.location.href;
    share_url+='&image='+i;
    share_url+='&noparse=1'
    return share_url;
}
function shareTW(title,desc,image) {
    t=encodeURIComponent(title);
    d=encodeURIComponent(desc);
    // u=encodeURIComponent(url);
    i=encodeURIComponent(image);
    share_url='http://twitter.com/intent/tweet';
    share_url+='?status='+d+' '+document.location.href;
    return share_url;
}

function socialShare(type,desc,image) {
    var u = '';
	var title = 'iPoint.kz'

    switch(type){
        case 'vk':
            u = shareVK(title,desc,image);
            break;
        case 'fb':
            u = shareFB(title,desc,image);
            break;
        case 'tw':
            u = shareTW(title,desc,image);
            break;
    }
    if(u != ''){
        window.open(u,'sharer','toolbar=0,status=0,width=626,height=436');
    }
    return false;
}


/*


var g_imagesContainer = null;

function handleImageMoved(e, imagesCurrent, imagesLength)
{
    $('#current').html(imagesCurrent.toString());
    $('.count').html(imagesLength.toString());
}

function handleResize(e, width, height)
{
    alert('New size is ' + width.toString() + 'x' + height.toString())
}

function initSlides(cycle)
{
    g_imagesContainer = $('#main-images-controller').asketicSwipe({
            cycle           : cycle,          //Cycle the gallery
            scale           : 1,              //To streach out low-res images on mobile web (for example same size x2 smaller images)
            tolerance       : 0.25,           //% of width for next image
            time            : 300,            //Transition time
            touchSensitivity: 10,            //Vertical sensitivity,
            fitContainer    : true,          //scale images to fit container
            fitContainerMargin: 0,          //px margin if images fitted to container
            fitContainerUpscale: false       //if upscaled when fitContainer is true
        });
}

$(document).ready(function(){
	

    initSlides(true);
    // iPhone & iPad Link
    if(navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/)) {
		$('#asketic-swipe-handler').live('click', function(){
			var currentIndex = g_imagesContainer.asketicSwipe.getImageIndex();
			window.location="/promotions/link/" + currentIndex;
			return false;
		})
	}

	// slides control
	var slides = g_imagesContainer.asketicSwipe.getImageCount();
	$('#controls-wrapper').css('width', (slides*15 + 10))

    // auto slides
	var interval = setInterval(function() {
		g_imagesContainer.asketicSwipe.next();
	}, 7000);

	$('.control').click(function(event) {
		// $('a').removeClass('active');
		// $(this).addClass('active');
		// 
		// var slideIndex = $(this).attr('rel')
		// g_imagesContainer.asketicSwipe.moveTo( slideIndex--, true );
		// 
		// return false;
	});
	
	

    $('#next').click(function(){
            g_imagesContainer.asketicSwipe.next();    
        });
    
    $('#prev').click(function(){
            g_imagesContainer.asketicSwipe.prev();    
        });
    
    $('#goto').click(function(){
            g_imagesContainer.asketicSwipe.moveTo( parseInt($('#index').val()) );    
        });
    
    $('#goto-animate').click(function(){
            g_imagesContainer.asketicSwipe.moveTo( parseInt($('#index').val()), true );    
        });
    
    $('#add-image').click(function(){
            var currentIndex = g_imagesContainer.asketicSwipe.getImageIndex();
            
            $('<li><img src="./images/4.jpg" width="187" height="204" /></li>').appendTo('#main-images-controller ul');
            g_imagesContainer.asketicSwipe.refresh();
            
            handleImageMoved(null, currentIndex, g_imagesContainer.asketicSwipe.getImageCount());
            
            g_imagesContainer.asketicSwipe.moveTo( currentIndex );  
        });
    
    $('#resize-container').click(function(){
            g_imagesContainer.asketicSwipe.resize(640, //height
                                                  480, //width
                                                  true, //animate or not
                                                  200, //time
                                                  'linear'); //easing
        });
    
    $('#enable').click(function(){
            g_imagesContainer.asketicSwipe.setEnabled( !g_imagesContainer.asketicSwipe.getEnabled() );
        });
    
    $('#cycle').change(function(){
        var currentIndex = g_imagesContainer.asketicSwipe.getImageIndex();
        
        initSlides( ($(this).attr('checked') == 'checked') );
        
        g_imagesContainer.asketicSwipe.moveTo( currentIndex );  
    });
    
    g_imagesContainer.bind('nextComplete', handleImageMoved);
    g_imagesContainer.bind('prevComplete', handleImageMoved);
    g_imagesContainer.bind('resizeComplete', handleResize);
    
    handleImageMoved(null, 0, g_imagesContainer.asketicSwipe.getImageCount());
});

*/





jQuery(document).ready(function(){
	
	var minWidth      = 1195
	var minHeight     = 730
	
	var deltaWidth	  = 0		// minWidth - $(window).width()
	var deltaHeight	  = 0		// minHeight - $(window).height()

	var defaultTop    = 25
	var defaultRight  = 157
	var defaultBottom = 20
	var defaultLeft   = 63

	// Center Docks on Mainpage
	function centerBlock(url, target){
		if (url == '/img/triggerTop.png' || url == '/img/triggerBottom.png') {
			// Width
			$(target).css({ left: ($(window).width() - $(target).outerWidth())/2 });
			
			// minHeight
			if ($(window).height() <= minHeight) {
				deltaHeight = minHeight - $(window).height()
				$('#triggerTop').css({ top: -1*(defaultTop + deltaHeight/2) });
				$('#triggerBottom').css({ bottom: -1*(defaultBottom + deltaHeight/2) });
			}
			
		} else {
			// Height
			$(target).css({ top: ($(window).height() - $(target).outerHeight())/2 });
			
			// minWidth
			if ($(window).width() <= minWidth) {
				deltaWidth = minWidth - $(window).width()
				$('#triggerRight').css({ right: -1*(defaultRight + deltaWidth/2) });
				$('#triggerLeft').css({ left: -1*(defaultLeft + deltaWidth/2) });
			}
		}
	}

	function smartBackgroundImage(url, target){
		if ($(target).css('display') == 'none') {
			//create an img so the browser will download the image:
			$('<img />')
			.attr('src', url)
			.load(function(){ //attach onload to set background-image

				// center
				centerBlock(url, target)
				$(target).css({display: '', opacity: 0})

				$(target).animate({opacity: 1}, 500, function(){
					switch (url) {
						case '/img/triggerTop.png':
							smartBackgroundImage('/img/triggerRight.jpg', $('#triggerRight'))
							break;

						case '/img/triggerRight.jpg':
							smartBackgroundImage('/img/triggerBottom.png', $('#triggerBottom'))
							break;

						case '/img/triggerBottom.png': 
							smartBackgroundImage('/img/triggerLeft.jpg', $('#triggerLeft'))
							break;

						default: 
							$('.sliderBlock, #slide-controls, .dnews, .bottom').fadeIn()
					}
				})
			})
		}
	}
	
	smartBackgroundImage('/img/triggerTop.png', $('#triggerTop'))	
	// smartBackgroundImage('/img/triggerRight.jpg', $('#triggerRight'))
	// smartBackgroundImage('/img/triggerBottom.png', $('#triggerBottom'))
	// smartBackgroundImage('/img/triggerLeft.jpg', $('#triggerLeft'))


	// .sliderBlock #slide-controls .dnews


	function moveIn(side) {
		$('#canvas').css({ bottom: 'auto', left: 'auto', top: 'auto', right: 'auto' })
		
		if (side == 'top') {
			$('#canvas').animate({top: '160px'}, 700, 'easeOutExpo')
			$('#dockTop').animate({top: '0'}, 700, 'easeOutExpo', function(){
				// turn on
				active = 'true'
			})

		} else if (side == 'right') {
			$('#dockRight').show()		// iPad fix
			$('#canvas').animate({right: '160px'}, 700, 'easeOutExpo')
			$('#dockRight').animate({right: '0'}, 700, 'easeOutExpo', function(){
				// turn on
				active = 'true'
			})

		} else if (side == 'bottom') {
			$('#dockBottom').show()		// iPad fix
			$('#canvas').animate({bottom: '160px'}, 700, 'easeOutExpo')
			$('#dockBottom').animate({bottom: '0'}, 700, 'easeOutExpo', function(){
				// turn on
				active = 'true'
			})

		} else if (side == 'left') {
			$('#canvas').animate({left: '160px'}, 700, 'easeOutExpo')
			$('#dockLeft').animate({left: '0'}, 700, 'easeOutExpo', function(){
				// turn on
				active = 'true'
			})
		}
	}

	function resetPosition(side,trig,rel) {
		if (side == 'top') {
			$('#dockTop').animate({top: '-160px'}, 500, 'easeOutExpo', function(){ $('#triggerTop').fadeIn() })
			$('#canvas').animate({ top: 0 }, 500, 'easeOutExpo', function(){
				trig.hide()
				moveIn(rel)
			})
			
		} else if (side == 'right') {
			$('#dockRight').animate({right: '-160px'}, 500, 'easeOutExpo', function(){ $('#triggerRight').fadeIn() })
			$('#canvas').animate({ right: 0 }, 500, 'easeOutExpo', function(){
				$('#dockRight').hide()			// iPad fix
				trig.hide()
				moveIn(rel)
			})
			
		} else if (side == 'bottom') {
			$('#dockBottom').animate({bottom: '-160px'}, 500, function(){ $('#triggerBottom').fadeIn() })
			$('#canvas').animate({ bottom: 0 }, 500, function(){
				$('#dockBottom').hide()			// iPad fix
				trig.hide()
				moveIn(rel)
			})
			
		} else if (side == 'left') {
			$('#dockLeft').animate({left: '-160px'}, 500, function(){ $('#triggerLeft').fadeIn() })
			$('#canvas').animate({ left: 0 }, 500, function(){
				trig.hide()
				moveIn(rel)
			})

		}
	}
	
	var active = 'true'
	$('.triggers').click(function(){
		
		// remove overuse
		if (active == 'false') return false
		active = 'false'
		
		var rel       = $(this).attr('rel')
		var trig      = $(this)
		var resetSide = false

		// $('.triggers').unbind('click')

		if (($('#dockRight').css('right').replace(/[^-\d\.]/g, '') == 0)) resetSide = 'right'
		if (($('#dockLeft').css('left').replace(/[^-\d\.]/g, '') == 0)) resetSide = 'left'
		if (($('#dockTop').css('top').replace(/[^-\d\.]/g, '') == 0)) resetSide = 'top'
		if (($('#dockBottom').css('bottom').replace(/[^-\d\.]/g, '' ) == 0)) resetSide = 'bottom'

		if (resetSide) {
			// reset
			resetPosition(resetSide, trig, rel)

		} else {	
			trig.hide()
			// move in
			moveIn(rel)
		}
	})
	
	$('.arrows').click(function(){

		if ( $('#dockRight').css('right').replace(/[^-\d\.]/g, '') == 0) {
			$('#canvas').animate({right: '0'}, 700, 'easeOutExpo')
			$('#dockRight').animate({right: '-160px'}, 700, 'easeOutExpo', function(){
				$('#dockRight').hide()			// iPad fix
				$('#triggerRight').fadeIn()
			})
		}
		
		if ( $('#dockLeft').css('left').replace(/[^-\d\.]/g, '') == 0) {
			$('#canvas').animate({left: '0'}, 700, 'easeOutExpo')
			$('#dockLeft').animate({left: '-160px'}, 700, 'easeOutExpo', function(){
				$('#triggerLeft').fadeIn()
			})
		}

		if ( $('#dockTop').css('top').replace(/[^-\d\.]/g, '') == 0) {
			$('#canvas').animate({top: '0'}, 700, 'easeOutExpo')
			$('#dockTop').animate({top: '-160px'}, 700, 'easeOutExpo', function(){
				$('#triggerTop').fadeIn()
			})
		}

		if ( $('#dockBottom').css('bottom').replace(/[^-\d\.]/g, '') == 0) {
			$('#canvas').animate({bottom: '0'}, 700, 'easeOutExpo')
			$('#dockBottom').animate({bottom: '-160px'}, 700, 'easeOutExpo', function(){
				$('#dockBottom').hide()			// iPad fix
				$('#triggerBottom').fadeIn()
			})
		}
	})
	
	$(window).resize(function(){

		// var minWidth      = 1195
		// var minHeight     = 730

		// var deltaWidth	  = 0		// minWidth - $(window).width()
		// var deltaHeight	  = 0		// minHeight - $(window).height()
		// 
		// var defaultTop    = 25
		// var defaultRight  = 157
		// var defaultBottom = 20
		// var defaultLeft   = 63
		
		// triggers align
		
		$('#triggerTop').css({ left: ($(window).width() - $('#triggerTop').outerWidth())/2 });
		$('#triggerRight').css({ top: ($(window).height() - $('#triggerRight').outerHeight())/2 });
		$('#triggerBottom').css({ left: ($(window).width() - $('#triggerBottom').outerWidth())/2 });
		$('#triggerLeft').css({ top: ($(window).height() - $('#triggerLeft').outerHeight())/2 });
		
		// products docks show
		$('.productDocks div').show()
		
		// docks align
		$('#dockTop').css({ left: ($(window).width() - $('#dockTop').outerWidth())/2 });
		$('#dockRight').css({ top: ($(window).height() - $('#dockRight').outerHeight())/2 });
		$('#dockBottom').css({ left: ($(window).width() - $('#dockBottom').outerWidth())/2 });
		$('#dockLeft').css({ top: ($(window).height() - $('#dockLeft').outerHeight())/2 });
		
		// minHeight
		if ($(window).height() <= minHeight) {
			deltaHeight = minHeight - $(window).height()
			$('#triggerTop').css({ top: -1*(defaultTop + deltaHeight/2) });
			$('#triggerBottom').css({ bottom: -1*(defaultBottom + deltaHeight/2) });
		}

		// minWidth
		if ($(window).width() <= minWidth) {
			deltaWidth = minWidth - $(window).width()
			$('#triggerRight').css({ right: -1*(defaultRight + deltaWidth/2) });
			$('#triggerLeft').css({ left: -1*(defaultLeft + deltaWidth/2) });
		}

	});
	
	
	// Product Docks
	var productDockOpen = $('.productDocks .arrows')
	if (productDockOpen.length > 0) {
		productDockOpen.unbind('click')

		productDockOpen.click(function(){
			var side = $(this).attr('id')

			if (side == 'arrowRight') {
				if (($('#dockRight').css('width').replace(/[^-\d\.]/g, '') == 45)) {
					$(this).removeClass('arRight')
					$(this).addClass('arLeft')
					$('#dockRight').animate({width: 155}, 500)
				} else {
					$(this).removeClass('arLeft')
					$(this).addClass('arRight')
					$('#dockRight').animate({width: 45}, 500)
				}
			}
			if (side == 'arrowBottom') {
				if (($('#dockBottom').css('height').replace(/[^-\d\.]/g, '') == 45)) {
					$(this).removeClass('arBottom')
					$(this).addClass('arTop')
					$('#dockBottom').animate({height: 155}, 500)
				} else {
					$(this).removeClass('arTop')
					$(this).addClass('arBottom')
					$('#dockBottom').animate({height: 45}, 500)
				}
				
			}

			if (side == 'arrowTop') {
				if (($('#dockTop').css('top').replace(/[^-\d\.]/g, '') == '-115')) {
					$(this).removeClass('arTop')
					$(this).addClass('arBottom')
					$('#dockTop').animate({top: 0}, 500)
				} else {
					$(this).removeClass('arBottom')
					$(this).addClass('arTop')
					$('#dockTop').animate({top: '-115px'}, 500)
				}
			}
			
			if (side == 'arrowLeft') {
				if (($('#dockLeft').css('left').replace(/[^-\d\.]/g, '') == '-115')) {
					$(this).removeClass('arLeft')
					$(this).addClass('arRight')
					$('#dockLeft').animate({left: 0}, 500)
				} else {
					$(this).removeClass('arRight')
					$(this).addClass('arLeft')
					$('#dockLeft').animate({left: '-115px'}, 500)
				}
			}

		})
	}
	
	// productDockOpen.click()
	
	// cart
	$('.updateProducts').click(function(){
		$('#formEditOrders').submit();
		return false;
	})
	
	
	// News on Mainpage
	if ($('#snews').length > 0) {
		$('#snews').dnews({ showdetail: false });
	}



	// Cart Edit
	var trigger_upd = $('.trigger_upd')
	var trigger_del = $('.trigger_del')
	trigger_upd.live('change', function(){
		update_cart()
	})
	trigger_del.live('click', function(){
		var item = $(this).parent().parent()	// select TR
		var oid  = $(this).attr('rel')			// Order ID

		if (confirm('Хотите удалить?')) {		// confirm
			item.remove();						// delete TR
			update_cart()

			// send request DELETE
			$.ajax({
				type: "POST",
				url: '/orders/delete',
				data: {'data[id]': oid}
			});
		}
	})
	function update_cart() {
		var oid
		var sum
		var sum_all = 0
		var update  = '{'
		var num     = $('.trigger_upd').length
		var i       = 1
		var format  = { numberOfDecimals: 0, decimalSeparator: '.', thousandSeparator: ' ' }
		$.each($('.trigger_upd'), function(index, value) { 
			oid = $(value).attr('rel')
			// calculate
			sum = $('#quantity'+oid).val() * $('#price'+oid).val()
			sum_all = sum_all + sum
			// update each item
			sum = $().number_format(sum, format);
			$('#total'+oid).text(sum)
			// data
			update += '"' + oid + '": ' + $('#quantity'+oid).val()
			if ( num != i ) update += ', '
			else update += '}'

			i++
		});
		// update total
		sum_all = $().number_format(sum_all, format);

		$('.total span').text(sum_all)

		// send request EDIT
		$.ajax({
			type: "POST",
			url: '/orders/edit',
			data: {'data[json]': update}
		});
	}
	
	// Products
	$('.online_order .prods').each(function(){
		var new_w = $(this).children().length * 96
		if (new_w > 855) new_w = 865

		$(this).css('width', new_w)
	})

	
})

$(function (){
	$('a.addToCart').click(function() {
		var url = this.href;
		var dialog = $('<div id="mydialog" style="display:none"></div>').appendTo('body');
		// load remote content
		dialog.load(
			url, 
			{}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
			function (responseText, textStatus, XMLHttpRequest) {
				dialog.dialog({
					width: 905,
					modal: true,
					title: 'Оформление заказа',
					// add a close listener to prevent adding multiple divs to the document
					close: function(event, ui) {
						// remove div with all data and events
						dialog.remove();
					}
				});
			}
		);
		//prevent the browser to follow the link
		return false;
	});

	// close Dialog on overlay Click & Product Click
	$('.name a').live('click', function() { $('#mydialog').dialog( "close" ); });
	$('.ui-widget-overlay').live('click', function() { $('#mydialog').dialog( "close" ); });


	

	// EqualHeight for Infoblocks
	function equalHeight(group) {
		var tallest = 0;
		group.each(function() {
			var thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		if (tallest < 150) tallest = 150;
		group.height(tallest);
	}
	if ($(".infoblock").length > 0) equalHeight($(".infoblock"));
});










$(window).load(function () {
	// To initially run the function:
	$(window).resize();

	// Show Product Dock on Start
	if ($('.productDocks .arrows').length > 0) {
		if ($('#dockRight').length > 0) $('#dockRight').animate({width: 45}, 500)
		if ($('#dockBottom').length > 0) $('#dockBottom').animate({height: 45}, 500)
		if ($('#dockTop').length > 0) 	$('#dockTop').animate({top: '-115px'}, 500)
		if ($('#dockLeft').length > 0) $('#dockLeft').animate({left: '-115px'}, 500)
	}

});
