//var $J = jQuery.noConflict();
jQuery(document).ready(function(){
	var rels = {};
	$('.lightbox').each(function(){
		var rel = $(this).attr('rel');
		if ( rel ) {
			rels[rel] = 1;
		} else {
			$(this).lightBox();    
		}
	});
	for ( var rel in rels ) {
		$('.lightbox[rel='+rel+']').lightBox();
	}	
	
	// Показ формы авторизации
	$('.show_auth_form').live('click',function() {
		closePopup();
		$.post(
			'/ru/ajax/',
			{
				giveForm:'auth'
			},
			function ( data ) {
				if ( data.result ) {
					$('#open_content').empty().prepend(data.data);
					showPopup();
				} else {
					$('body').append(data.data);
				}
			},
			'json'
		);
	});
	
	//	Авторизация через ПопАп
	
	$('#AuthMe').live('click',function() {
		var login = trim( $('#login_auth').val() );
		var pass = trim( $('#pass_auth').val() );
		var err = new Array();
		var location = window.location.pathname;
		$('#open_error').hide().empty();
		showSnake('on','#open');
		if ( empty(login) ) {
			err['login'] = get_lang('auth','login_empty');
		}
		if ( empty(pass) ) {
			err['pass'] = get_lang('auth','pass_empty');
		}
		//alert(err);
		if ( count(err) > 0 ) {
			var errS = '<ul>';
			for ( i in err ) {
				errS = errS + '<li>'+err[i]+'</li>';
			}
			errS = errS + '</ul>';
			showSnake('off','#open');
			$('#open_error').html(errS).show('slow');
		} else {
			$.post(
				'/ru/auth/',
				{
					lets_auth: true,
					url: location,
					auth_pass: md5(pass),
					auth_login: login
				},
				function (data) {
					if ( data.result ) {
						$('#open_error').css({'color':'green'}).html(data.data).show('fast');
//						if ( file_get_contents(window.location) > 0 ) var go_to = window.location;
//							else var go_to = '/';
//						var go_to = '/';
						setTimeout( function() { window.location = data.tourl } , 600 );
						showSnake('off','#open');
					} else {
						$('#open_error').html(data.data).show('slow');
						showSnake('off','#open');
					}
				},
				'json'
			);
		}
	});
	
	//	Авторизация на главной
	
	$('#AuthMeOnMain').live('click',function() {
		var login = trim( $('#login_auth').val() );
		var pass = trim( $('#pass_auth').val() );
		var err = new Array();
		var snakePos = $('#AuthMeOnMain').parent();
		$('#AuthOnMainErrors').empty();
		//showSnake('on','#AuthOnMainErrors');
		showSnake('on',snakePos);
		if ( empty(login) ) {
			err['login'] = get_lang('auth','login_empty');
		}
		if ( empty(pass) ) {
			err['pass'] = get_lang('auth','pass_empty');
		}

		if ( count(err) > 0 ) {
			var errS = '<ul>';
			for ( i in err ) {
				errS = errS + '<li>'+err[i]+'</li>';
			}
			errS = errS + '</ul>';
			closePopup();
			showSnake('off',snakePos);
			$('#open_content').empty().prepend('<span style="color:red;">'+errS+'</span>');
			showPopup();
			//$('#AuthOnMainErrors').html(errS);
		} else {
			$.post(
				'/ru/auth/',
				{
					lets_auth: true,
					auth_pass: md5(pass),
					auth_login: login
				},
				function (data) {
					if ( data.result ) {
						$('#AuthOnMainErrors').css({'color':'green'}).html(data.data).show('fast');
						$('form[name="auth_form"]"').hide();
						setTimeout( function() { window.location = window.location} , 600 );
						showSnake('off',snakePos);
					} else {
						closePopup();
						showSnake('off',snakePos);
						$('#open_content').empty().prepend('<span style="color:red;">'+data.data+'</span>');
						showPopup();
						//$('#AuthOnMainErrors').html(data.data).show('slow');
						
					}
				},
				'json'
			);
		}
	});
	
	
	// покаать форму регистрации
	$('#letsRegisterMe').live('click',function() {
		closePopup();
		var data = $.ajax({
			url: '/ru/ajax/',
			async: false,
			type: "POST",
			dataType: "json",
			data: ({ giveForm:'registration' }),
			success: function ( data ) {
		        if ( data.result ) {
		           //return dt =  data.data;
		           return data.data;
		        } else {
		           return false;
		        }
		    }
		}).responseText;
		data = $.parseJSON(data)
		$('#open_content').empty().prepend(data.data);
		showPopup();
		$('#registrationForm input[name="phone"]').mask('+7(999)999-99-99');
	});
	
	// Процесс регистрации
	$('#letsRegisterMeData').live('click',function() {
		var pss = trim($('#registrationForm input[name="pass"]').val());
		var pss2 = trim($('#registrationForm input[name="pass2"]').val());
		
		if ( empty(pss) || empty(pss2) ) {
			alert(get_lang('registration','form_pass_empty'));
		} else {
		
			$('#registrationForm input[name="pass"]').val(md5(pss));
			$('#registrationForm input[name="pass2"]').val(md5(pss2));
			var arr = $('#registrationForm').serializeArray();
			showSnake('on','#open');
		
			$.post(
				'/ru/registration/',
				{
					lets_reg:true,
					data:arr
				},
				function(data) {
					if ( data.result ) {
						showSnake('off','#open');
						closePopup();
						$('#open_content').css({'color':'green'}).prepend(data.data);
						showPopup();
						//setTimeout( function() { window.location = window.location} , 600 );
					
					} else {
						$('#captcha_captcha_online').attr('src','/captcha/?' + String(Math.random()));
						$('#registrationForm input[name="captcha"]').val('');
						$('#registrationForm input[name="pass"]').val('');
						$('#registrationForm input[name="pass2"]').val('');
						$('#open_error').html(data.data).show('slow');
						showSnake('off','#open');
					}
				},
				'json'
			);
		}
	});
	
	
	// покаать форму забыли пароль
	$('#forgotMyPass').live('click',function() {
		closePopup();
		var data = $.ajax({
			url: '/ru/ajax/',
			async: false,
			type: "POST",
			dataType: "json",
			data: ({ giveForm:'pass_forgot' }),
			success: function ( data ) {
		        if ( data.result ) {
		           //return dt =  data.data;
		           return data.data;
		        } else {
		           return false;
		        }
		    }
		}).responseText;
		data = $.parseJSON(data)
		$('#open_content').empty().prepend(data.data);
		showPopup();
	});
	
	// Послать запрос 
	$('#forgotPassFormGo').live('click',function() {
		showSnake('on','#open');
		var arr = $('#forgotPassForm').serializeArray();
		$.post(
			'/ru/forget_pass/',
			{
				ajaxAction:'recover_pass',
				data:arr
			},
			function(data) {
				if ( data.result ) {
					showSnake('off','#open');
					closePopup();
					$('#open_content').css({'color':'green'}).prepend(data.data);
					showPopup();
					//setTimeout( function() { window.location = window.location} , 600 );
				} else {
					$('#open_error').html(data.data).show('slow');
					showSnake('off','#open');
				}
			},
			'json'
		);
	});
	
	
	//закрыть попап
	$('.close, #opaco').live('click',function(){
		closePopup();
	return false;
	});
    
    /*$('a').focus(function(){
        $(this).blur();
    });*/
	// Активный саб меню
	//var active_sub = $('.submenu a.active').parent().attr('id');
	// Показать родитель если пункт активный
	//$('.submenu a.active').parent().show(); //.attr('dd',"DD")
	
	/*if ( $('.main_menu_item').is('.active') ) {
		$('#'+$('.main_menu_item.active').attr('my_sub') ).show();
	}*/
	
	$('.main_menu_item').hover(function() {
		var this_child = $(this).attr('my_sub');
		//$('.submenu').hide();
		$('#'+this_child).show();
	},function(){
		var this_child = $(this).attr('my_sub');
		//$('.submenu').hide();
		$('#'+this_child).hide();
	});
	
	/*$('#menu td').mouseleave(function() {
		$('.submenu').hide();
		//$('#'+active_sub).show();
		//$('#'+$('.main_menu_item.active').attr('my_sub') ).show();
	});*/
	//menu
    /*$("#menu td").hover(function(){
		$("ul:first:hidden", this).slideDown(200);
	},function(){
		$("ul:first:visible", this).slideUp(150);
	});*/
    $("#menu .submenu").hover(function(){
		$(this).show();
	},function(){
		$(this).hide();
	});
	
    $("#menu ul a").hover(function(){
		$(this).css("background", "#f4f4f4").parent().css("background", "#f4f4f4");
	},function(){
		$(this).css("background", "#fff").filter(":not(.active)").parent().css("background", "#fff");
	});
	$("#menu ul a.active").parent().css("background", "#f4f4f4");

	
	carousel1();
	carousel2();
	
	$("#menu1, #menu1_").hover(function(){
		$('#menu1_').show();
	},function(){
		$('#menu1_').hide();
	});
	$("#menu2, #menu2_ > *").hover(function(){
		$('#menu2_').show();
	},function(){
		$('#menu2_').hide();
	});
	
    $('input.add_to_basket').click(function() {
        var del_action = $(this).attr('act');
        var url = $(this).parents('form.myAddBasketForm').attr('action');
        var qnt = $(this).parents('form.myAddBasketForm').find('input[name="quantity"]').val();
        var remove_form = $(this).parent();
        if ( trim(qnt) == '' || qnt == 0 ) {
            alert($(this).parent().find('input[name="quantity"]').attr('desc'));
            return false;
        } else {
            url = url+qnt+'/';
            $.post(
                url,
                {ajaxAction: 'add_to_basket'},
                function ( data ) {
                
                    if ( data.result ) {
                        $('td.basket div').empty().html(data.data);
                        if ( del_action != 'no_del' ) {
                            remove_form.replaceWith('<a href="/ru/basket/" class="bask">'+data.inbasket+'</a>');
                        }
                    } else {
                        alert('Ошибка при добавлении товара в корзину');
                    }
                },
                "json"
            );
        }
        return false;
    });

    $('input.add_to_compare').click(function(){
        var url = $(this).parents('form.myAddCompareForm').attr('action');
        var remove_form = $(this).parent().parent();
            $.post(
                url,
                {ajaxAction: 'add_to_compare'},
                function ( data ) {
                    if ( data.result ) {
                        $('a.compare b').empty().html(data.data);
                        remove_form.html('<a href="/ru/compare/" class="bask">'+data.incompare+'</a>');
                    } else {
                      alert('Ошибка при добавлении товара в сравнение');
                    }
                },
                "json"
            );
        return false;
    });
    // Процесс установления нового пароля
	$('#forgotPassNewPassFormGo').live('click',function() {
//		var pss = $('#forgotPassNewPassForm input[name="pass"]').val();
//		$('#forgotPassNewPassForm input[name="pass"]').val(md5(pss));
//		var pss2 = $('#forgotPassNewPassForm input[name="pass2"]').val();
//		$('#forgotPassNewPassForm input[name="pass2"]').val(md5(pss2));
		var arr = $('#forgotPassNewPassForm').serializeArray();
		showSnake('on','#open');
		$.post(
			'/ru/forget_pass/',
			{
				ajaxAction:'news_pass',
				data:arr
			},
			function(data) {
				if ( data.result ) {
					showSnake('off','#open');
					closePopup();
					$('#open_content').css({'color':'green'}).prepend(data.data);
					showPopup();
					//setTimeout( function() { window.location = window.location} , 600 );
				} else {
					$('#forgotPassNewPassForm input[name="pass"]').val('');
					$('#forgotPassNewPassForm input[name="pass2"]').val('');
					$('#open_error').html(data.data).show('slow');
					showSnake('off','#open');
				}
			},
			'json'
		);
	});
	
	$('.compare_holder #table_head .table_strips').width($('.compare_holder #table_compare .table_strips').width());
	$('.bt_del').live('click',function(){
		$('.compare_holder #table_head .table_strips').width($('.compare_holder #table_compare .table_strips').width());
	});
    
});

//	показ формы смены пароля
function ForgetPassLetsMakeNewPass(user_id)
{
	closePopup();
	var data = $.ajax({
		url: '/ru/ajax/',
		async: false,
		type: "POST",
		dataType: "json",
		data: ({ giveForm:'pass_forgot_new_pass', user_id:user_id }),
		success: function ( data ) {
	        if ( data.result ) {
	           //return dt =  data.data;
	           return data.data;
	        } else {
	           return false;
	        }
	    }
	}).responseText;
	data = $.parseJSON(data)
	$('#open_content').empty().prepend(data.data);
	showPopup();
}

// popup
function closePopup(){
	$('#opaco').addClass('hidden').removeAttr('style');
	$('#open').addClass('hidden');
	$('#open_content').empty().removeAttr('style');
	$('#open_error').hide().empty().removeAttr('style');
	return false;
}
function refresh_captcha(id,input_id)
{
	$('#'+input_id).val('');
	$('#'+id).attr('src','/captcha/?' + String(Math.random()));
}
function showPopup(){
	if($.browser.msie){
		$('#opaco').height($(document).height()).removeClass('hidden');
	} else {
		$('#opaco').height($(document).height()).removeClass('hidden').fadeTo('slow', 0.7);
	};
	$('#open').alignCenter().removeClass('hidden');
	return false;
}

$.fn.alignCenter = function() {
	var marginLeft = Math.max(40, parseInt($(window).width()/2 - $(this).width()/2)) + 'px';
	var marginTop = Math.max(40, parseInt($(window).height()/2 - $(this).height()/2)) + 'px';
	return $(this).css({'margin-left':marginLeft, 'margin-top':marginTop});
};


function get_lang(table,field)
{
	var data = $.ajax({
		url: '/ru/ajax/',
		async: false,
		type: "POST",
		dataType: "json",
		data: ({ajaxAction:'get_lang',table:table, field:field}),
		success: function ( data ) {
            if ( data.result ) {
               //return dt =  data.data;
               return data.data;
            } else {
               return false;
            }
        }
	}).responseText;
	data = $.parseJSON(data)
	return data.data;
}

// asynchronously
function get_lang2(table,field)
{  
    //var dt = "";
    $.post(
        '/ru/ajax/',
        {ajaxAction:'get_lang',table:table, field:field},
        function ( data ) {
            if ( data.result ) {
               //return dt =  data.data;
               return data.data;
            } else {
               return false;
            }
        },
        "json"
    );
    //setTimeout(function(){alert(dt)},600);
}

$(window).resize(function(){
	carousel1();
	carousel2();
	$('.compare_holder #table_head .table_strips').width($('.compare_holder #table_compare .table_strips').width());

});


function add_to_basket(item)
{
    
}

function carousel1() {
	$(".carousel").jCarouselLite({
		btnNext: "#carousel .next",
		btnPrev: "#carousel .prev",
		circular: false,
		visible: 3,
		speed: 800
	}); 
}
function carousel2() {
	$(".carousel_b").jCarouselLite({
		btnNext: "#carousel_b .next",
		btnPrev: "#carousel_b .prev",
		circular: false,
		visible: 5,
		speed: 800
	}); 
}
function count (mixed_var, mode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Waldo Malqui Silva
    // +      bugfixed by: Soren Hansen
    // +      input by: merabi
    // +      improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
    // *     returns 1: 6
    // *     example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
    // *     returns 2: 6

    var key, cnt = 0;

    if (mixed_var === null){
        return 0;
    } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object){
        return 1;
    }

    if (mode === 'COUNT_RECURSIVE') {
        mode = 1;
    }
    if (mode != 1) {
        mode = 0;
    }

    for (key in mixed_var){
        if (mixed_var.hasOwnProperty(key)) {
            cnt++;
            if ( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
                cnt += this.count(mixed_var[key], 1);
            }
        }
    }

    return cnt;
}

function showSnake(onOff,where)
{
	if ( onOff == 'on' ) {
		//alert(pos);
		//if ( pos == 'pre' ) $(where).prepend('<div class="snake"><img src="/data/snake.gif"></div>');
		$(where).prepend('<div class="snake"><img src="/data/snake.gif"></div>');
	}
	if ( onOff == 'off' ) {
		$(where).find('.snake').remove();
	}
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0,
        i = 0;
    str += '';


    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }

    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }

    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function empty (mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    var key;

    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}


// Инициализируем таблицу перевода
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8; // Ё
trans[0x451] = 0xB8; // ё

// Переопределяем функцию md5()
function md5(str)
{
	var ret = [];
	// Переводим кириллицу
	for (var i = 0; i < str.length; i++) {
		var n = str.charCodeAt(i);
		if (typeof trans[n] != 'undefined') n = trans[n];
		if (n <= 0xFF) ret.push(n);
	}
	// Теперь работаем по стандартной схеме - (вместо --calcMD5--каждый подставляет имя своей функции md5 шифрования и в качестве параметра String.fromCharCode.apply(null, ret))
	return md52(String.fromCharCode.apply(null, ret));
}




function md52 (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: md5('Kevin van Zonneveld');
    // *     returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'
    var xl;

    var rotateLeft = function (lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    };

    var addUnsigned = function (lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    };

    var _F = function (x, y, z) {
        return (x & y) | ((~x) & z);
    };
    var _G = function (x, y, z) {
        return (x & z) | (y & (~z));
    };
    var _H = function (x, y, z) {
        return (x ^ y ^ z);
    };
    var _I = function (x, y, z) {
        return (y ^ (x | (~z)));
    };

    var _FF = function (a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _GG = function (a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _HH = function (a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _II = function (a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var convertToWordArray = function (str) {
        var lWordCount;
        var lMessageLength = str.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = new Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    };

    var wordToHex = function (lValue) {
        var wordToHexValue = "",
            wordToHexValue_temp = "",
            lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            wordToHexValue_temp = "0" + lByte.toString(16);
            wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2);
        }
        return wordToHexValue;
    };

    var x = [],
        k, AA, BB, CC, DD, a, b, c, d, S11 = 7,
        S12 = 12,
        S13 = 17,
        S14 = 22,
        S21 = 5,
        S22 = 9,
        S23 = 14,
        S24 = 20,
        S31 = 4,
        S32 = 11,
        S33 = 16,
        S34 = 23,
        S41 = 6,
        S42 = 10,
        S43 = 15,
        S44 = 21;

    str = this.utf8_encode(str);
    x = convertToWordArray(str);
    a = 0x67452301;
    b = 0xEFCDAB89;
    c = 0x98BADCFE;
    d = 0x10325476;

    xl = x.length;
    for (k = 0; k < xl; k += 16) {
        AA = a;
        BB = b;
        CC = c;
        DD = d;
        a = _FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = _FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = _FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = _FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = _FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = _FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = _FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = _FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = _FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = _FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = _FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = _FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);

        a = _FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = _FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = _FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = _FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = _GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = _GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = _GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = _GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = _GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = _GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = _GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = _GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = _GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = _GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = _GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = _GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = _GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = _GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = _GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = _GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = _HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = _HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = _HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = _HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = _HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = _HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = _HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = _HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = _HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = _HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = _HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = _HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = _HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = _HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = _HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = _HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = _II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = _II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = _II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = _II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = _II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = _II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = _II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = _II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = _II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = _II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = _II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = _II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = _II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = _II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = _II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = _II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = addUnsigned(a, AA);
        b = addUnsigned(b, BB);
        c = addUnsigned(c, CC);
        d = addUnsigned(d, DD);
    }

    var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);

    return temp.toLowerCase();
}

function utf8_encode (argString) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);
            }
            utftext += enc;
            start = end = n + 1;
        }
    }

    if (end > start) {
        utftext += string.slice(start, stringl);
    }

    return utftext;
}


function file_get_contents (url, flags, context, offset, maxLen) {
    // Read the entire file into a string
    //
    // version: 906.111
    // discuss at: http://phpjs.org/functions/file_get_contents
    // +   original by: Legaev Andrey
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Raphael (Ao) RUDLER
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain without modifications.
    // %        note 2: Synchronous by default (as in PHP) so may lock up browser. Can
    // %        note 2: get async by setting a custom "phpjs.async" property to true and "notification" for an
    // %        note 2: optional callback (both as context params, with responseText, and other JS-specific
    // %        note 2: request properties available via 'this'). Note that file_get_contents() will not return the text
    // %        note 2: in such a case (use this.responseText within the callback). Or, consider using
    // %        note 2: jQuery's: $('#divId').load('http://url') instead.
    // %        note 3: The context argument is only implemented for http, and only partially (see below for
    // %        note 3: "Presently unimplemented HTTP context options"); also the arguments passed to
    // %        note 3: notification are incomplete
    // *     example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    // Note: could also be made to optionally add to global $http_response_header as per http://php.net/manual/en/reserved.variables.httpresponseheader.php
    var tmp, headers = [],
        newTmp = [],
        k = 0,
        i = 0,
        href = '',
        pathPos = -1,
        flagNames = 0,
        content = null,
        http_stream = false;
    var func = function (value) {
        return value.substring(1) !== '';
    };

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    var ini = this.php_js.ini;
    context = context || this.php_js.default_streams_context || null;

    if (!flags) {
        flags = 0;
    }
    var OPTS = {
        FILE_USE_INCLUDE_PATH: 1,
        FILE_TEXT: 32,
        FILE_BINARY: 64
    };
    if (typeof flags === 'number') { // Allow for a single string or an array of string flags
        flagNames = flags;
    } else {
        flags = [].concat(flags);
        for (i = 0; i < flags.length; i++) {
            if (OPTS[flags[i]]) {
                flagNames = flagNames | OPTS[flags[i]];
            }
        }
    }

    if (flagNames & OPTS.FILE_BINARY && (flagNames & OPTS.FILE_TEXT)) { // These flags shouldn't be together
        throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()';
    }

    if ((flagNames & OPTS.FILE_USE_INCLUDE_PATH) && ini.include_path && ini.include_path.local_value) {
        var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\';
        url = ini.include_path.local_value + slash + url;
    } else if (!/^(https?|file):/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url())
        href = this.window.location.href;
        pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8) - 1 : href.lastIndexOf('/');
        url = href.slice(0, pathPos + 1) + url;
    }

    if (context) {
        var http_options = context.stream_options && context.stream_options.http;
        http_stream = !! http_options;
    }

    if (!context || http_stream) {
        var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
        if (!req) {
            throw new Error('XMLHttpRequest not supported');
        }

        var method = http_stream ? http_options.method : 'GET';
        var async = !! (context && context.stream_params && context.stream_params['phpjs.async']);

        if (ini['phpjs.ajaxBypassCache'] && ini['phpjs.ajaxBypassCache'].local_value) {
            url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(); // Give optional means of forcing bypass of cache
        }

        req.open(method, url, async);
        if (async) {
            var notification = context.stream_params.notification;
            if (typeof notification === 'function') {
                // Fix: make work with req.addEventListener if available: https://developer.mozilla.org/En/Using_XMLHttpRequest
                if (0 && req.addEventListener) { // Unimplemented so don't allow to get here
/*
                    req.addEventListener('progress', updateProgress, false);
                    req.addEventListener('load', transferComplete, false);
                    req.addEventListener('error', transferFailed, false);
                    req.addEventListener('abort', transferCanceled, false);
                    */
                } else {
                    req.onreadystatechange = function (aEvt) { // aEvt has stopPropagation(), preventDefault(); see https://developer.mozilla.org/en/NsIDOMEvent
                        // Other XMLHttpRequest properties: multipart, responseXML, status, statusText, upload, withCredentials
/*
    PHP Constants:
    STREAM_NOTIFY_RESOLVE   1       A remote address required for this stream has been resolved, or the resolution failed. See severity  for an indication of which happened.
    STREAM_NOTIFY_CONNECT   2     A connection with an external resource has been established.
    STREAM_NOTIFY_AUTH_REQUIRED 3     Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
    STREAM_NOTIFY_MIME_TYPE_IS  4     The mime-type of resource has been identified, refer to message for a description of the discovered type.
    STREAM_NOTIFY_FILE_SIZE_IS  5     The size of the resource has been discovered.
    STREAM_NOTIFY_REDIRECTED    6     The external resource has redirected the stream to an alternate location. Refer to message .
    STREAM_NOTIFY_PROGRESS  7     Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
    STREAM_NOTIFY_COMPLETED 8     There is no more data available on the stream.
    STREAM_NOTIFY_FAILURE   9     A generic error occurred on the stream, consult message and message_code for details.
    STREAM_NOTIFY_AUTH_RESULT   10     Authorization has been completed (with or without success).

    STREAM_NOTIFY_SEVERITY_INFO 0     Normal, non-error related, notification.
    STREAM_NOTIFY_SEVERITY_WARN 1     Non critical error condition. Processing may continue.
    STREAM_NOTIFY_SEVERITY_ERR  2     A critical error occurred. Processing cannot continue.
    */
                        var objContext = {
                            responseText: req.responseText,
                            responseXML: req.responseXML,
                            status: req.status,
                            statusText: req.statusText,
                            readyState: req.readyState,
                            evt: aEvt
                        }; // properties are not available in PHP, but offered on notification via 'this' for convenience
                        // notification args: notification_code, severity, message, message_code, bytes_transferred, bytes_max (all int's except string 'message')
                        // Need to add message, etc.
                        var bytes_transferred;
                        switch (req.readyState) {
                        case 0:
                            //     UNINITIALIZED     open() has not been called yet.
                            notification.call(objContext, 0, 0, '', 0, 0, 0);
                            break;
                        case 1:
                            //     LOADING     send() has not been called yet.
                            notification.call(objContext, 0, 0, '', 0, 0, 0);
                            break;
                        case 2:
                            //     LOADED     send() has been called, and headers and status are available.
                            notification.call(objContext, 0, 0, '', 0, 0, 0);
                            break;
                        case 3:
                            //     INTERACTIVE     Downloading; responseText holds partial data.
                            bytes_transferred = req.responseText.length * 2; // One character is two bytes
                            notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0);
                            break;
                        case 4:
                            //     COMPLETED     The operation is complete.
                            if (req.status >= 200 && req.status < 400) {
                                bytes_transferred = req.responseText.length * 2; // One character is two bytes
                                notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0);
                            } else if (req.status === 403) { // Fix: These two are finished except for message
                                notification.call(objContext, 10, 2, '', req.status, 0, 0);
                            } else { // Errors
                                notification.call(objContext, 9, 2, '', req.status, 0, 0);
                            }
                            break;
                        default:
                            throw 'Unrecognized ready state for file_get_contents()';
                        }
                    }
                }
            }
        }

        if (http_stream) {
            var sendHeaders = http_options.header && http_options.header.split(/\r?\n/);
            var userAgentSent = false;
            for (i = 0; i < sendHeaders.length; i++) {
                var sendHeader = sendHeaders[i];
                var breakPos = sendHeader.search(/:\s*/);
                var sendHeaderName = sendHeader.substring(0, breakPos);
                req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos + 1));
                if (sendHeaderName === 'User-Agent') {
                    userAgentSent = true;
                }
            }
            if (!userAgentSent) {
                var user_agent = http_options.user_agent || (ini.user_agent && ini.user_agent.local_value);
                if (user_agent) {
                    req.setRequestHeader('User-Agent', user_agent);
                }
            }
            content = http_options.content || null;
/*
            // Presently unimplemented HTTP context options
            var request_fulluri = http_options.request_fulluri || false; // When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.
            var max_redirects = http_options.max_redirects || 20; // The max number of redirects to follow. Value 1 or less means that no redirects are followed.
            var protocol_version = http_options.protocol_version || 1.0; // HTTP protocol version
            var timeout = http_options.timeout || (ini.default_socket_timeout && ini.default_socket_timeout.local_value); // Read timeout in seconds, specified by a float
            var ignore_errors = http_options.ignore_errors || false; // Fetch the content even on failure status codes.
            */
        }

        if (flagNames & OPTS.FILE_TEXT) { // Overrides how encoding is treated (regardless of what is returned from the server)
            var content_type = 'text/html';
            if (http_options && http_options['phpjs.override']) { // Fix: Could allow for non-HTTP as well
                content_type = http_options['phpjs.override']; // We use this, e.g., in gettext-related functions if character set
                //   overridden earlier by bind_textdomain_codeset()
            } else {
                var encoding = (ini['unicode.stream_encoding'] && ini['unicode.stream_encoding'].local_value) || 'UTF-8';
                if (http_options && http_options.header && (/^content-type:/im).test(http_options.header)) { // We'll assume a content-type expects its own specified encoding if present
                    content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1]; // We let any header encoding stand
                }
                if (!(/;\s*charset=/).test(content_type)) { // If no encoding
                    content_type += '; charset=' + encoding;
                }
            }
            req.overrideMimeType(content_type);
        }
        // Default is FILE_BINARY, but for binary, we apparently deviate from PHP in requiring the flag, since many if not
        //     most people will also want a way to have it be auto-converted into native JavaScript text instead
        else if (flagNames & OPTS.FILE_BINARY) { // Trick at https://developer.mozilla.org/En/Using_XMLHttpRequest to get binary
            req.overrideMimeType('text/plain; charset=x-user-defined');
            // Getting an individual byte then requires:
            // responseText.charCodeAt(x) & 0xFF; // throw away high-order byte (f7) where x is 0 to responseText.length-1 (see notes in our substr())
        }

        if (http_options && http_options['phpjs.sendAsBinary']) { // For content sent in a POST or PUT request (use with file_put_contents()?)
            req.sendAsBinary(content); // In Firefox, only available FF3+
        } else {
            req.send(content);
        }

        tmp = req.getAllResponseHeaders();
        if (tmp) {
            tmp = tmp.split('\n');
            for (k = 0; k < tmp.length; k++) {
                if (func(tmp[k])) {
                    newTmp.push(tmp[k]);
                }
            }
            tmp = newTmp;
            for (i = 0; i < tmp.length; i++) {
                headers[i] = tmp[i];
            }
            this.$http_response_header = headers; // see http://php.net/manual/en/reserved.variables.httpresponseheader.php
        }

        if (offset || maxLen) {
            if (maxLen) {
                return req.responseText.substr(offset || 0, maxLen);
            }
            return req.responseText.substr(offset);
        }
        return req.responseText;
    }
    return false;
}

