var base_url = '';
var shoppingbag_update_url = '';
var productAdd2Bag_url = '';
var newsletter_subscription_url = '';
var article_media_height = 100;
var article_media_width = 100;
var news_media_height = 100;
var news_media_width = 100;
var msg_title_error = 'STATICTEXT:Error';
var msg_title_success = 'STATICTEXT:Success';
var msg_title_confirm = 'STATICTEXT:Confirm';
var msg_btn_ok = 'STATICTEXT:OK';
var msg_btn_save = 'STATICTEXT:Save';
var msg_btn_cancel = 'STATICTEXT:Cancel';
var msg_btn_yes = 'STATICTEXT:Yes';
var msg_btn_no = 'STATICTEXT:No';
var msg_btn_send = 'STATICTEXT:Send';
var msg_btn_reply = 'STATICTEXT:Reply';
var msg_btn_lookbook_prev = 'STATICTEXT:Prev';
var msg_btn_lookbook_next = 'STATICTEXT:Next';
var msg_btn_lookbook_zoom = 'Zoom';

var lock = false;

$.extend({
	_enc_div: null,
	htmlenc: function(val) {
		if (this._enc_div == null) this._enc_div = $('<div />');
		this._enc_div.text(val);
		return this._enc_div.html().replace(/\n/g, "<br />");
	},
	htmldec: function(val) {
		if (this._enc_div == null) this._enc_div = $('<div />');
		this._enc_div.html(val);
		return this._enc_div.text();
	},
	preload_images: function(images, pointer, callback) {
		if (images.length > pointer) {
			$('<img />').load(function() {
				$.preload_images(images, pointer + 1, callback);
			}).attr('src', images[pointer]);
		} else {
			callback();
		}
	},
	intValue: function(val, min, max) {
		var v = $.trim(val);
		if (v == '') {
			return null;
		}
		v = parseInt(v, 10);
		if (isNaN(v)) {
			return null;
		}
		return Math.min(max, Math.max(min, v));
	},
	floatValue: function(val, min, max, precision) {
		if (precision === undefined) {
			precision = 2;
		}
		var v = $.trim(val);
		if (v == '') {
			return null;
		}
		v = parseFloat(v.replace(/,/, '.'));
		if (isNaN(v)) {
			return null;
		}
		var multiplier = Math.round(Math.pow(10, precision));
		return Math.min(max, Math.max(min, Math.round(v * multiplier) / multiplier));
	}
});

// fixes the problem of assigning a null value to the controls in IE
(function(oldVal) {
	$.fn.val = function(value) {
		if (arguments.length) {
			return oldVal.call(this, (value === undefined || value === null) ? '' : value);
		} else {
			return oldVal.call(this);
		}
	};
})($.fn.val);

function show_error_dialog(title, message, callback, is_modal) {
	var buttons = [];
	buttons[msg_btn_ok] = function() {
		$(this).dialog('close');
	};
	$("#message_dialog")
		.dialog("destroy")
		.attr('title', title)
		.find('p')
			.attr('class', 'error_dlg')
			.html($.htmlenc(message))
			.end()
		.dialog({
			width: 400,
			height: 'auto',
			modal: is_modal,
			buttons: buttons,
			close: function() {
				callback && callback();
			}
		});
}

function show_info_dialog(title, message, callback, is_modal) {
	var buttons = [];
	buttons[msg_btn_ok] = function() {
		$(this).dialog('close');
	};
	$("#message_dialog")
		.dialog("destroy")
		.attr('title', title)
		.find('p')
			.attr('class', 'information_dlg')
			.html($.htmlenc(message))
			.end()
		.dialog({
			width: 400,
			height: 'auto',
			modal: is_modal,
			buttons: buttons,
			close: function() {
				callback && callback();
			}
		});
}

function show_confirm_dialog(title, message, callback, is_modal) {
	var buttons = [];
	buttons[msg_btn_yes] = function() {
		$(this).dialog('close');
		callback && callback();
	};
	buttons[msg_btn_no] = function() {
		$(this).dialog('close');
	};
	buttons[msg_btn_cancel] = function() {
		$(this).dialog('close');
	};
	$("#message_dialog")
		.dialog("destroy")
		.attr('title', title)
		.find('p')
			.attr('class', 'confirm_dlg')
			.html($.htmlenc(message))
			.end()
		.dialog({
			width: 400,
			height: 'auto',
			modal: is_modal,
			buttons: buttons
		});
}

$(function() {
	if (lock) return;
	lock = true;

	// setup the ajax event handler for processing indicator
	$('#ajax_communication_indicator').ajaxStart(function() {
		  $(this).show();
	}).ajaxStop(function() {
		  $(this).hide();
	});

	// let the popup forms submit by pressing on enter
	$('div.popup_editor>form:first-child').append($('<input type="submit" class="hidden" />')).submit(function() {
		$('>.ui-dialog-buttonpane > button:first', $(this).parent().parent()).trigger('click');
		return false;
	});

});

/*
 * iphone/ipad utilities
 *
 */
var iPhoneUtil = {

    // private variables
    _isIPad: undefined,
    _isIPhone: undefined,
    _isIPod: undefined,
    _isIMobileDevice: undefined,

    /**
     * check if the device is iPad
     *
     */
    isIPad: function() {
        if (this._isIPad === undefined) this._isIPad = (navigator.userAgent.indexOf('iPad') != -1);
        return this._isIPad;
    },


    /**
     * check if the device is iPhone
     *
     */
    isIPhone: function() {
        if (this._isIPhone === undefined) this._isIPhone = (navigator.userAgent.indexOf('iPhone') != -1);
        return this._isIPhone;
    },


    /**
     * check if the device is iPod
     *
     */
    isIPod: function() {
        if (this._isIPod === undefined) this._isIPod = (navigator.userAgent.indexOf('iPod') != -1);
        return this._isIPod;
    },

    /**
     * checks if a device is an apple mobile device
     *
     */
    isIMobileDevice: function() {
        if (this._isIMobileDevice === undefined) this._isIMobileDevice = this.isIPhone() || this.isIPad() || this.isIPod();
        return this._isIMobileDevice;
    },

    /**
     * check if the application is running in a standalone mode
     *
     */
    isStandalone: function() {
        return window.navigator.standalone;
    },


    /**
     * updates an orientation of the device
     *
     */
    updateOrientation: function() {
        document.body.className = (window.orientation == 0 || window.orientation == 180) ? "portrait" : "landscape";
    },


    /**
     * initializes the device orientation tracking
     *
     */
    initOrientationTracking: function() {
        this.updateOrientation();
        var t = this;
        window.onorientationchange = function() {
            t.updateOrientation();
            t.hideURLBar();
        };
    },


    /**
     * hides the URL and Debug bar of the browser window
     *
     */
    hideURLBar: function() {
        setTimeout(function() {
            scrollTo(0, 0);
        }, 0);
    },


    /**
     * slides the top URL and Debug bars away from the screen on start
     *
     */
    hideURLBarOnLoad: function() {
    	$(window).load($.proxy(function() {
            this.hideURLBar;
        }, this));
    },


    /**
     * handles the links click in the standalone mode
     *
     */
    fullscreenLinksClickHandler: function(e) {
        /* ignore elements with a target value specified since "target" cannot be handled in full-screen mode those links shall open regularly in Mobile Safari */
        if (!!$(this).attr('target')) return;

        var url = $(this).attr('href');

        /* ignore links other than HTTP(S) and to different origin */
        var match = url.match(/^https?:\/\/(.+?)\/.*$/);
        if (!match || match[1] != window.location.host) return;

        /* finally open the link in full-screen view and prevent default behavior */
        window.location.href = url;
        e.preventDefault();
    },

    /**
     * preliminary initialization of the application before the document load
     *
     */
    appPreLoadInitialization: function() {
        if (!this.isIMobileDevice()) return;
        this.hideURLBarOnLoad();
    },


    /**
     * on document ready initialization of the application
     *
     */
    appPostLoadInitialization: function() {
        if (!this.isIMobileDevice()) return;
        this.initOrientationTracking();
        if (this.isStandalone()) {
            $('#').addClass('fullscreen');
            $('a').click(this.fullscreenLinksClickHandler);
        }
    }
};


/*******************************************************
 * FingerSwipe class
 * implements the finger swipe emulation on touch devices
 * 
 *******************************************************/
function FingerSwipe(client, parameters) {
	this.downX = null;
	this.upX = null;
	this.downY = null;
	this.upY = null;
	this.client = client;
	this.parameters = parameters || {};

	if (iPhoneUtil.isIMobileDevice()) {
		$(client)
			.bind('touchstart', $.proxy(this.onTouchStart, this))
			.bind('touchmove', $.proxy(this.onTouchMove, this))
			.bind('touchend', $.proxy(this.handleSwipe, this))
		;
	}
	
	// emulate the swipe with mouse moves?
	if ((this.parameters.emulateMouse === undefined) || this.parameters.emulateMouse) {
		$(client)
			.mousedown($.proxy(this.onMouseDown, this))
			.mouseup($.proxy(this.onMouseUp, this))
		;
	}

	return this;
}

FingerSwipe.prototype = {
	'onMouseDown': function(event) {
		event.preventDefault();
		this.downX = event.pageX;
		this.downY = event.pageY;
	},
	'onMouseUp': function(event) {
		this.upX = event.pageX;
	    this.upY = event.pageY;
	    this.handleSwipe(event);
	},
	'onTouchStart': function(event) {
		var touch = event.originalEvent.touches[0];
		this.upX = this.downX = touch.pageX;
		this.upY = this.downY = touch.pageY;
		this.parameters.onStart && this.parameters.onStart(this.upX, this.upY); 
	},
	'onTouchMove': function(event) {
		event.preventDefault();
		var touch = event.originalEvent.touches[0];
		this.upX = touch.pageX;
		this.upY = touch.pageY;
		this.parameters.onMove && this.parameters.onMove(this.downX - this.upX, this.downY - this.upY); 
	},
	'handleSwipe': function(event) {
		var xDiff = this.downX - this.upX;
		if (xDiff > 50) {
			event.preventDefault();
			this.parameters.onSwipeLeft && this.parameters.onSwipeLeft(-xDiff); 
	    } else if (xDiff < -50) {
	    	event.preventDefault();
	    	this.parameters.onSwipeRight && this.parameters.onSwipeRight(xDiff); 
	    }
	}
};




/**
 *	Main site functions
 */

var shoppingbagPullDown = {
	'shoppingbagform_pulldown': null,
	'open_shoppingbag_pulldown': null,
	'shoppingbag_table': null,
	'shoppingbag_count': null,


	/**
	 * object initialization
	 *
	 */
	'init': function() {
		this.open_shoppingbag_pulldown = $('#shoppingbag_link');
		this.shoppingbagform_pulldown = $('#shoppingbag_full');
		this.shoppingbag_table = $('#shoppingbag_table');
		this.shoppingbag_count = $('#shoppingbag_count');
		this.open_shoppingbag_pulldown.click(function(e) { e.preventDefault(); shoppingbagPullDown.formToggle(); });
	},

	'formToggle': function() {
		if (this.opened) {
			this.formPullUp();
		} else {
			this.formPullDown();
		}
	},

	'formPullDown': function() {
		topPulldowns.allPullUp();
		var t = this;
		this.shoppingbagUpdate(function() {
			t.shoppingbagform_pulldown.slideDown("fast", function(){
				t.opened = true;
				t.open_shoppingbag_pulldown.addClass('opened');
			});
		});
	},

	'formPullUp': function() {
		if (this.opened) {
			var t = this;
			this.shoppingbagform_pulldown.slideUp("fast", function(){
				t.opened = false;
				t.open_shoppingbag_pulldown.removeClass('opened');
			});
		}
	},

	'shoppingbagUpdate': function(callback) {
		$("tbody>tr", this.shoppingbag_table).remove();
		var subtotalCell = $("tfoot>tr.total>td.total", this.shoppingbag_table);
		var whereInsertRows = $("tbody", this.shoppingbag_table);
		subtotalCell.empty();
		$.getJSON(
			shoppingbag_update_url + '?r=' + Math.random(),
			null,
			function(data) {
				if (data.status == 0) {
					shoppingbagPullDown.shoppingbag_count.html(data.count);
					subtotalCell.html(data.subTotal);
					$.each(data.dataRows, function(i, item){
						var row = $('<tr >');
						row.append($('<td />').html(item.amount).addClass('amount'));
						row.append($('<td />').html(item.name).addClass('item'));
						row.append($('<td />').html(item.total).addClass('total'));
						whereInsertRows.append(row);
				    });
					if (data.count < 1) {
						$('#shoppingbag_container').addClass('hidden');
					} else {
						$('#shoppingbag_container').removeClass('hidden');
					}
					callback && callback();
				} else {
					// TODO: implement error handling?
					show_error_dialog(msg_title_error, data.message, null, true);
				}
			}
		);
	}
};


var topPulldowns = {
	allPullUp: function() {
		shoppingbagPullDown.formPullUp();
	}
};


var lookbookImages = {
	list: null,
	cycleSet: null,
	theBody: null,
	cycle_current_element: null,
	nav_zoom: null,
	init: function() {
		this.list = $('#lookbook_image_list>a');
		this.theBody = $('body');
		if (this.theBody && this.list.length > 0) {
			// if we have lookbook images, load them, then show all stuff.
			// init image cycle set
			this.cycleSet = $('<div />').addClass('hidden lookbook_backimage').prependTo(this.theBody);
			// load first image and set call back to display it and load rest
			var t = this;
			var loadSet = function(images, index) {
				var img = $('<img />').load(function() {

					if (index == 0) {
						// show first image immediatly
						t.showFirstImage();
					}

					loadSet(images, index + 1);
					if (index + 1 >= images.length) {
//						shoppingbagPopup.Show(function(){
							t.initNavigation();
//						});
					};
				});
				img.attr('src', images[index]);
			};
			loadSet(this.list, 0);
		} else {
			// just shopping bag
//			shoppingbagPopup.justShow();
		}
	},

	initNavigation: function() {
		var i;
		for(i=1; i < lookbookImages.list.length; i++) {
			lookbookImages.cycleSet.append($('<div />').css({opacity: 0, backgroundImage: 'url("'+lookbookImages.list[i]+'")'}));
		}
		

		if (iPhoneUtil.isIMobileDevice()) { 
						
			lookbookImages.cycleSet.cycle({
				timeout: 0,
			    containerResize: 0,
			    slideResize: 0,
			    speed: 600,
			    fx: 'scrollHorz',
			    after: function(currSlideElement, nextSlideElement) {
			    	$('#ajax_loader').hide();
			    	lookbookImages.cycle_current_element = nextSlideElement;
			    	var background_url = $(lookbookImages.cycle_current_element).css('background-image');
					background_url = background_url.replace('url("', '');
					background_url = background_url.replace('")', '');
	
					var tmp_img = $('<img />').attr({src: background_url});
					$('body').append(tmp_img);
	
					
						if ((tmp_img.height() < document.body.clientHeight) || (tmp_img.width() < document.body.clientWidth)) {
							$('#lookbook_zoom').css({ 'display': 'none'});
						} else {
							$('#lookbook_zoom').css({ 'display': 'block'});
						}
						tmp_img.remove();
					
					
			    }
			});
			
			
			// add a finger swipe support for mobile devices
			new FingerSwipe($('body'), {
				'onSwipeRight': $.proxy(function() {
					 $('#ajax_loader').show();
					 $('.lookbook_backimage').cycle('prev');
					 setTimeout(function() {
						 $('#ajax_loader').hide();
						}, 200);
				}, this),
				'onSwipeLeft': $.proxy(function() {
					 $('.lookbook_backimage').cycle('next');
					 $('#ajax_loader').show();
					 setTimeout(function() {
						 $('#ajax_loader').hide();
						}, 200);
				}, this)
			});
			
			
			
		} else {
			var nav_next = $('<a />').text(msg_btn_lookbook_next).attr({id: 'lookbook_next'}).mousemove(function(e) {
				var off = $(this).offset();
				$(this).css({backgroundPosition: Math.min(e.pageX - off.left, $(this).width() - 73) + 'px ' + Math.min(e.pageY - off.top, $(this).height() - 73) + 'px'});
			});
			nav_next.insertAfter('#page');
			var nav_prev = $('<a />').text(msg_btn_lookbook_prev).attr({id: 'lookbook_prev'}).mousemove(function(e) {
				var off = $(this).offset();
				$(this).css({backgroundPosition: Math.min(e.pageX - off.left, $(this).width() - 73) + 'px ' + Math.min(e.pageY - off.top, $(this).height() - 73) + 'px'});
			});
			nav_prev.insertAfter('#page');
			var nav_zoom = $('<a />').text(msg_btn_lookbook_zoom).attr({id: 'lookbook_zoom'}).mousemove(function(e) {
				var off = $(this).offset();
				$(this).css({backgroundPosition: Math.min(e.pageX - off.left, $(this).width() - 70) + 'px ' + Math.min(e.pageY - off.top, $(this).height() - 70) + 'px'});
			});
			nav_zoom.insertAfter('#page');
			
			
			lookbookImages.cycleSet.cycle({
				prev: '#lookbook_prev',
			    next: '#lookbook_next',
			    timeout: 0,
			    containerResize: 0,
			    slideResize: 0,
			    speed: 600,
	
			    after: function(currSlideElement, nextSlideElement) {
	
			    	lookbookImages.cycle_current_element = nextSlideElement;
			    	var background_url = $(lookbookImages.cycle_current_element).css('background-image');
					background_url = background_url.replace('url("', '');
					background_url = background_url.replace('")', '');
	
					var tmp_img = $('<img />').attr({src: background_url});
					$('body').append(tmp_img);
	
					setTimeout(function() {
						if ((tmp_img.height() < document.body.clientHeight) || (tmp_img.width() < document.body.clientWidth)) {
							$('#lookbook_zoom').css({ 'display': 'none'});
						} else {
							$('#lookbook_zoom').css({ 'display': 'block'});
						}
						tmp_img.remove();
					}, 200);
			    }
			});
		}
		
		
		var timer_resize = null;
		
		$(window).bind('resize', function() {
			
			
			if (timer_resize) {
				clearTimeout(timer_resize);
			}
			
			timer_resize = setTimeout(function() {
				var background_url = $(lookbookImages.cycle_current_element).css('background-image');
				background_url = background_url.replace('url("', '');
				background_url = background_url.replace('")', '');

				var tmp_img = $('<img />').load(function () {
					if ((tmp_img[0].height < document.body.clientHeight) || (tmp_img[0].width < document.body.clientWidth)) {
						$('#lookbook_zoom').css({ 'display': 'none'});
					} else {
						$('#lookbook_zoom').css({ 'display': 'block'});
					}
					
				}).attr({src: background_url});
				
				
			}, 400);
			
			
		});		
		
		$('#page').css({ display: 'none' });

		if (!iPhoneUtil.isIMobileDevice()) { 
			nav_zoom.click(function(e) {
				e.preventDefault();
				lookbookImages.initMyZoom();
			});
		}

	},
	initMyZoom: function() {
			$('.map-viewport').remove();

			var background_url = $(lookbookImages.cycle_current_element).css('background-image');
			background_url = background_url.replace('url("', '');
			background_url = background_url.replace('")', '');


			var map1container = $('<div />').css({height: document.body.clientHeight + 'px', width: document.body.clientWidth + 'px' }).addClass('map-viewport');
			var zoom_img = $('<img />').attr({src: background_url}).addClass('level');
			var zoom = $('<div />').attr('id', 'map-2');

			zoom.append(zoom_img);
			map1container.append(zoom);
			$('body').append(map1container);

			$('#map-2').css({ height: zoom_img.height() + 'px', width: zoom_img.width() + 'px' });
			zoom_img.remove();

			$('#map-2').css({ backgroundImage: 'url("' + background_url + '")' })

			setTimeout(function() {
				$('body').append(map1container);


				if (($('#map-2').width() > document.body.clientWidth) && ($('#map-2').height() > document.body.clientHeight)) {

					$('.lookbook_backimage').css({ display: 'none' });
					$('#lookbook_prev').hide();
					$('#lookbook_next').hide();
					$('#lookbook_zoom').hide();
					$('#close_zoom').remove();

					var timer = null;

					var onresize = function() {
						if (timer) {
							clearTimeout(timer);
						}
						
						timer = setTimeout(function() {
							lookbookImages.initMyZoom();
						}, 400);

					};
					
					$(window).bind('resize', onresize);

					lookbookImages.dehbokZoom($('.map-viewport').width(), $('.map-viewport').height(), $('#map-2').width(), $('#map-2').height());

					var close_zoom = $('<a />').attr({id: 'close_zoom'});
					close_zoom.insertAfter('#page');

					close_zoom.click(function(e) {
						e.preventDefault();
						$('.lookbook_backimage').css({ display: 'block' });
						$('#lookbook_prev').show();
						$('#lookbook_next').show();
						$('#lookbook_zoom').show();
						$('.map-viewport').remove();
						$('#close_zoom').remove();
						
						
						$(window).unbind('resize', onresize);
					});


				} else {
					$('.lookbook_backimage').css({ display: 'block' });
					$('#lookbook_prev').css({ display: 'block' });
					$('#lookbook_next').css({ display: 'block' });
					$('#lookbook_zoom').css({ display: 'block' });
					$('.map-viewport').remove();
					$('#close_zoom').remove();
					$(window).unbind('resize');
					
					
				}
			}, 400);



			//$('#map-2').css({ height: zoom_img.height() + 'px', width: zoom_img.width() + 'px' });
			//$('.cloud-zoom').css({ height: document.body.clientHeight + 'px', width: document.body.clientWidth + 'px' });



	},
	dehbokZoom: function(sW, sH, bW, bH) {
		$(".map-viewport").mousemove(function(event) {
			  
			  var ratioX = event.pageX/sW;
			  var ratioY = event.pageY/sH;

			  var cX = ((ratioX*bW) - event.pageX) * (-1);
			  var cY = ((ratioY*bH) - event.pageY) * (-1);

			  $('#map-2').css({ top: cY, left: cX });

		});
	},

	showFirstImage: function() {
		this.cycleSet.show();
		this.cycleSet.append($('<div />').css({backgroundImage: 'url("'+this.list[0]+'")'}));
	}

};


var articlesNavigation = {
	articles_images_container: null,
	navigation_arrow_left: null,
	navigation_arrow_right: null,

	/**
	 * object initialization
	 *
	 */
	init: function() {
		this.articles_images_container = $('#articles_images_container');

		if (this.articles_images_container) {
			artilces_images = $('ul.article_slider>li', this.articles_images_container);
			if (!artilces_images.length) return;
			if (artilces_images.length == 1) return;
			this.navigation_arrow_left = $('#articles_left_arrow');
			this.navigation_arrow_right = $('#articles_right_arrow');
			$('ul>li', this.articles_images_container).removeClass('hidden');
			var start = artilces_images.index($('.current'));
			if (artilces_images.length > 1) {
				this.navigation_arrow_right.show();
			}
			if (start >= artilces_images.length-1) {
				this.navigation_arrow_right.hide();
			}
			if (start > 0) {
				this.navigation_arrow_left.show();
			}

			var loopInterval = null;
			var isLooped = false;
			this.articles_images_container.serialScroll({
				"target":		'#articles_images_window',
				"items":		'li',
				"prev":			'#articles_left_arrow',
				"next":			'#articles_right_arrow',
				"axis": 		'x',
				"duration":		250,
				"start":		start,
				"force":		true,
				"cycle":		isLooped,
				"interval":		loopInterval,
				"onAfter":		function (elem) {
					$('#articles_texts_container>div.current').removeClass('current').addClass('hidden');
					$('#'+$(elem).attr('id').replace('images', 'text')).addClass('current').removeClass('hidden');
				},
				"onBefore":		function (e, elem, $pane, $items, pos) {
					/**
					 * 'this' is the triggered element
					 * e is the event object
					 * elem is the element we'll be scrolling to
					 * $pane is the element being scrolled
					 * $items is the items collection at this moment
					 * pos is the position of elem in the collection
					 * if it returns false, the event will be ignored
					 */
					//those arguments with a $ are jqueryfied, elem isn't.
					e.preventDefault();
					if (this.blur) this.blur();

					// update arrows
					if (pos == 0) {
						articlesNavigation.navigation_arrow_left.hide();
					} else if (pos > 0) {
						articlesNavigation.navigation_arrow_left.show();
					}
					if (pos == ($items.length - 1)) {
						articlesNavigation.navigation_arrow_right.hide();
					} else if (pos < ($items.length - 1)) {
						articlesNavigation.navigation_arrow_right.show();
					}
					$items.removeClass('current');
					$(elem).addClass('current');

					articleBigImages.initCycle();
				}
			});

            new FingerSwipe(this.articles_images_container, {
                onSwipeLeft: $.proxy(function(diff) {
                	$('#articles_left_arrow').trigger('click');
                }, this),
                onSwipeRight: $.proxy(function(diff) {
                	$('#articles_right_arrow').trigger('click');
                }, this)
            });

		}
	}
};


var articleBigImages = {
	currentCycle: [],
	current_element: null,

	init: function() {
		this.initCycle();
	},

	initCycle: function() {
		if (this.currentCycle.length > 0) {
			this.currentCycle.each(function(i, e) {
				e.cycle('destroy');
			});
			this.currentCycle = [];
		}
		var containers = $('div.bigimages_container');
		var t = this;
		containers.each(function(i, e) {
			var $e = $(e);
			var cc = $e.cycle({
				next: $('div.bigimage_circle', $e),
				timeout: 0,
				after: function (currSlideElement, nextSlideElement) {
					articleBigImages.current_element = nextSlideElement;

				}
			});
 			t.currentCycle.push(cc);




		});
	}

};


var productBigImages = {
	currentCycle: null,
	init: function() {
		this.initCycle();
	},

	initCycle: function() {
		if (this.currentCycle) {
			this.currentCycle.cycle('destroy');
			this.currentCycle = null;
		}
		this.currentCycle = $('#product_images_window>div.bigimages_container').cycle({
		    next: '#product_images_window>div.bigimages_container>div>div.bigimage_circle',
		    timeout: 0
		});
	}

};


/****************************************************************************************
* Page fadein/fadeout effect
*
* fades a page in to on load
* The page should contain a div with id="page_fader" as a first element of the <body>:
* 	<div id="page_fader"></div>
*
* The page would not fade in if the <body> has class "nofadein"
*
* To fade out the page the following code must be run:
* 	pagefader.fadeOut(callback);
* where callback is the function to execute when the fade completes
*
* The color of fade transition is set in the screen.css (white):
*	#page_fader {
* 		...
*		background: #fff;
*	}
*
****************************************************************************************/
var pagefader = {
	fadeLayer: null,

	/**
	 * object initialization
	 *
	 */
	init: function() {
		this.fadeLayer = $('#page_fader');
		if (!this.fadeLayer) return;
		// init the fade-in effect for just opened page
		if (this.fadeLayer.css('display') == 'none') return;
		this.fadeLayer.animate({opacity: 0, avoidTransforms: true}, 'slow', 'linear', function() {
			pagefader.fadeLayer.css({display: 'none'});
		});
	},


	/**
	 * fades the page out
	 *
	 */
	fadeOut: function(callback) {
		if (!this.fadeLayer) return;

		this.fadeLayer.css({display: 'block', opacity: 0});
		this.fadeLayer.animate({opacity: 1, avoidTransforms: true}, 'slow', 'linear', $.proxy(callback, this));
	}
};

var superZoom = {
		'init': function() {


			if ($('#news_article_container').length) {
				var nav_zoom = $('<a />').text(msg_btn_lookbook_zoom).addClass('article_zoom').mousemove(function(e) {
	 				var off = $(this).offset();
	 				$(this).css({backgroundPosition: Math.min(e.pageX-35 - off.left, $(this).width() - 70) + 'px ' + Math.min(e.pageY-35 - off.top, $(this).height() - 70) + 'px'});
	 			});
	 			nav_zoom.prependTo('.one_slide');


	 			$('.article_zoom').click(function(e) {
					e.preventDefault();
					$('.bigimages_container').css({'display': 'none'});



					var map1container = $('<div />').css({ height: '531px', width: '758px', marginBottom: '24px' }).addClass('map-viewport');
					var zoom_img = $('<img />').attr({src: $('.hidden_link', articleBigImages.current_element).attr('href')  }).addClass('level');
					var zoom = $('<div />').attr('id', 'map-1');

					zoom.append(zoom_img);
					map1container.append(zoom);

					map1container.prependTo($('#news_article_container'));

					setTimeout(function(){
						$('#map-1').css({ 'width': zoom_img.width(), 'height': zoom_img.height() });
						$("#map-1").mapz();
					},300);


					var close_zoom = $('<a />').attr({id: 'close_zoom'});
					close_zoom.appendTo('.map-viewport');

					close_zoom.click(function(e) {
						e.preventDefault();

						$('.bigimages_container').css({'display': 'block'});

						$('.map-viewport').remove();
						$('#close_zoom').remove();

					});
				});
			}
		}
}
var productAdd2Bag = {
	'forms': null,

	/**
	 * object initialization
	 *
	 */
	'init': function() {
		if (!shoppingbagPullDown) return;
		this.forms = $('form.buy_form');
		this.forms.submit($.proxy(function(e){ e.preventDefault(); this.addProduct2Bag(e); return false;}, this));
	},

	'addProduct2Bag': function(event) {
		if (event.currentTarget.product_id) {
			var productId = parseInt($(event.currentTarget.product_id).val());
			if (productId) {
				$.post(
					productAdd2Bag_url,
					{'product_id': productId},
					function(data) {
						if (data.status == 0) {
							shoppingbagPullDown.formPullDown();
						} else {
							show_error_dialog(msg_title_error, data.message, null, true);
						}
					},
					'json'
				);

			}
		}
	}
};





$(document).ready(function() {
	// iphone specific initializations
	iPhoneUtil.appPreLoadInitialization();
	
	
	 //superZoom.init();
	//var pageW = (-1)*($('#page').width()/2);
	//$('#page').css({ 'margin-left': pageW + 'px' });
});

/**
 *	Main site functions init
 */
$(function() {
	shoppingbagPullDown.init();

	lookbookImages.init();
	articleBigImages.init();

//	articlesNavigation.init();
//	productBigImages.init();

	productAdd2Bag.init();

	/* init <select> if not webkit */
	if (!$.browser.webkit) {
		$('select.selectmenu').selectmenu();
	};

	$('audio').mediaelementplayer();
	$('video.article').mediaelementplayer({'defaultVideoWidth': article_media_width, 'defaultVideoHeight': article_media_height, 'enableAutosize': false});
	$('video.news').mediaelementplayer({'defaultVideoWidth': news_media_width, 'defaultVideoHeight': news_media_height, 'enableAutosize': false});

	pagefader.init();

});

